2012-11-07 80 views
2

我正在写一个python代码来从.txt文件中提取所有信息。我已经写代码,但来到永诺错误:“NoneType”对象有没有属性“groupdict”python re 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() 

请帮帮我吧!谢谢!

+4

这意味着你的're.match'永远不会匹配任何东西......你确定你不应该使用're.search'吗? [它可能有助于显示一些示例输入数据...] –

+0

匹配方法,如果字符串与模式不匹配,则返回None类型,如 – felipsmartins

回答

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将返回无和存储在m。所以mNone。然后,您尝试从m拨打电话groupdict,您会收到上述错误。因此,在继续处理之前,您应该首先检查m是否为None

+0

Thx!虽然我改为re.reasch,但它不起作用......或者groupdict函数可以用match函数构建? –