Python:逐行读取以查找regex和组中的不工作

2024-06-16 13:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个纯文本文件,我想用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搜索的结果。在

我做错什么了?在


Tags: inimportreforsearchlinegroupresult
2条回答

如果re.search找不到匹配项,则返回None。因此,在访问m.group(1)之前,最好先检查if m:。在

另外,您很可能需要将整个文件读入内存,因为您的匹配跨越多行。只需将.*替换为.*?,并在编译regex时使用re.DOTALL修饰符,这样.可以匹配换行符号。在

尝试使用with逐行读取文件,然后打开它进行读取:

with open('guion.fountain', 'r') as file:
        result = []
        for line in file:
                m = re.search("\[\[Prop\]\]\*(.*)\*", line)
                result.append(m.group(1))
....

相关问题 更多 >