我正在编写一个Python代码来从.txt中提取所有信息。我已经编写了代码,但总是出现错误:'NoneType'对象没有属性'groupdict'
代码:
import re
readfile = open("test.txt")
try:
all_the_text =readfile.read()
m = re.match("(pdflink=[\w\s/]*)author=([\w\s/]*/n)",unicode(all_the_text),flags=re.UNICODE)
m.groupdict()
print m.groupdict()
finally:
readfile.close()
writefile = open('test5.txt','w')
print >> writefile, m.groupdict()
writefile.close()
请帮帮我!谢谢!
最佳答案
来自 Python 文档:
re.match(模式、字符串、标志=0)¶
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的 MatchObject 实例。如果字符串与模式不匹配,则返回 None;请注意,这与零长度匹配不同
在您的代码中,re.match 返回 None 并将其存储在 m
中。所以m
是None
。然后,您尝试从 m
调用 groupdict
,并收到上述错误。因此,在继续处理之前,您应该首先检查 m
是否为 None
。
关于python re 与 groupdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261349/