所以我有一个纯文本文件,我想用python来查找所有regex并列出所有结果。在
这是我在交互式控制台上尝试的:
>>> import re
>>> result = []
>>> file = open('guion.fountain')
>>> for line in file:
... m = re.search("\[\[Prop\]\]\*(.*)\*", line)
... result.append(m.group(1))
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
但我没有运气。它表示m
变量是NotType
,而不是regexp搜索的结果。在
我做错什么了?在
如果
re.search
找不到匹配项,则返回None
。因此,在访问m.group(1)
之前,最好先检查if m:
。在另外,您很可能需要将整个文件读入内存,因为您的匹配跨越多行。只需将
.*
替换为.*?
,并在编译regex时使用re.DOTALL
修饰符,这样.
可以匹配换行符号。在尝试使用
with
逐行读取文件,然后打开它进行读取:相关问题 更多 >
编程相关推荐