Python循环中的正则表达式

3

试图爬取天气状况(列表v中的索引9),并将变量保存以备后用。但是写正则表达式以存储仅为1或2个单词的条件时遇到了困难。

在regexr.com上测试了我的正则表达式代码,看起来很好,但在IDLE中运行时无效。

v = ['\n\n7:53 AM\n\n\n\n\n',
 '\n\n\n\n\n\n48 \nF\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n45 \nF\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n89 \n%\n    \n\n\n\n\n\n\n',
 '\n\nSE\n\n\n\n\n',
 '\n\n\n\n\n\n5 \nmph\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n0 \nmph\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n30.11 \nin\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n0.0 \nin\n    \n\n\n\n\n\n\n',
 '\n\nMostly Cloudy\n\n\n\n\n']

for condition in str(v[9]):
        condition_search = re.findall('[A-Z]\w+', condition)
        if len(condition_search) > 1:
            condition = ' '
            condition = condition.join(condition_search)
        else:
            condition = str(condition_search)

print(condition)

实际结果:

'[]'

期望结果

'Mostly Cloudy'

if re.search(r'^[A-Z]\w*(?:\s+[A-Z]\w*)?$', v[9].strip()): condition = v[9].strip() - Wiktor Stribiżew
不需要循环。你可以使用join()函数与只有一个元素的列表,这样就不需要测试了。 - Barmar
3个回答

3

正则表达式很好,但我认为你要找的是.strip()

text='\n\nMostly Cloudy\n\n\n\n\n'
print(text.strip())

结果:

Mostly Cloudy

并且周围的空格被去掉了。
(在 https://docs.python.org/3/library/stdtypes.html 上查找文档)


2
也许,这只会返回这个:
import re
v = ['\n\n7:53 AM\n\n\n\n\n',
     '\n\n\n\n\n\n48 \nF\n    \n\n\n\n\n\n\n',
     '\n\n\n\n\n\n45 \nF\n    \n\n\n\n\n\n\n',
     '\n\n\n\n\n\n89 \n%\n    \n\n\n\n\n\n\n',
     '\n\nSE\n\n\n\n\n',
     '\n\n\n\n\n\n5 \nmph\n    \n\n\n\n\n\n\n',
     '\n\n\n\n\n\n0 \nmph\n    \n\n\n\n\n\n\n',
     '\n\n\n\n\n\n30.11 \nin\n    \n\n\n\n\n\n\n',
     '\n\n\n\n\n\n0.0 \nin\n    \n\n\n\n\n\n\n',
     '\n\nMostly Cloudy\n\n\n\n\n']

condition_search = re.findall(r'[A-Z][A-Za-z\s]+[a-z]', v[9])

print(condition_search[0])

输出

Mostly Cloudy

如果您想要简化/修改/探索表达式,可以在regex101.com的右上角面板中找到解释。如果您愿意,您还可以在此链接中观看如何匹配一些示例输入。


正则表达式电路图

jex.im 可以可视化正则表达式:

enter image description here


1
他想要返回一个字符串,而不是一个列表。 - Barmar
1
太好了,谢谢大家!我认为如果我在上面使用pop,我可以快速转换为字符串。 - Amocat _

2

假设您正在获取一些天气数据的爬取,我认为您获得的数据以某种方式标准化。

查看数据可以发现,您需要的信息前后都有很多换行和空格字符(这些是不需要的)。为了去除它们:

更简单的非正则表达式解决方法:

# This removes the leading and trailing white-space characters in each line,
# which also includes space, newline, tabs, etc,.
processed_weather_data = [line.strip() for line in v]

# Lets say you need weather condition which is at the 9th index
print(processed_weather_data[9])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接