2012-11-07 77 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函數構建? –