python与groupdict

时间:2012-11-07 00:02:01

标签: python

我正在编写一个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()

请帮帮我! THX!

1 个答案:

答案 0 :(得分:2)

来自Python文档:

re.match(pattern, string, flags=0)¶ If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match

在您的代码中,re.match返回None并将其存储在m中。因此mNone。然后,您尝试从groupdict调用m,然后您会收到上述错误。因此,在继续处理之前,您应先检查m是否为None