2017-04-04 33 views
0

我有以下Python代碼:的Python - AttributeError的: 'NoneType' 對象有沒有屬性 '組'

import re 

terms = {} 
numbers = {} 

meshFile = 'file.bin' 
with open(meshFile, mode='rb') as file: 
    mesh = file.readlines() 

outputFile = open('mesh.txt', 'w') 

for line in mesh: 
    meshTerm = re.search(b'MH = (.+)$', line) 
    term = meshTerm.group(1) 
    meshNumber = re.search(b'MN = (.+)$', line) 
    number = meshNumber.group(1) 
    numbers[str(number)] = term 
    if terms.has_key(term): 
     terms[term] = terms[term] + ' ' + str(number) 
    else: 
     terms[term] = str(number) 

print(terms) 

當我運行代碼,我收到以下錯誤:

Traceback (most recent call last): 
    File "myFile.py", line 14, in <module> 
    term = meshTerm.group(1) 
AttributeError: 'NoneType' object has no attribute 'group' 

我該如何解決這個問題?

謝謝。

回答

2

該錯誤告訴您沒有匹配的組。打印您的line變量,然後將其傳遞到re.search,並檢查meshNumber是否爲None

1

當你在做meshTerm = re.search(b'MH = (.+)$', line)這個。這裏返回None。它應該是正則表達式對象。

+0

正如[答案]中所述,請避免回答不清楚,過寬,錯字,不可重複或重複的問題。編寫我的代碼請求和費力的家庭作業問題不適用於[所以],更適合於專業編碼/輔導服務。良好的問題堅持[問],包括[mcve],有研究的努力,並有潛力對未來的訪問者有用。回答不適當的問題會使網站變得更難以瀏覽和鼓勵更多這樣的問題,從而損害其他用戶的志願者時間和專業知識。 – TigerhawkT3

相關問題