我有很多句子,但是我會創建一個函數來分別對每個句子進行操作。所以輸入只是一個字符串。我的主要目標是提取在"near blue meadows"
之類的介詞後面的單詞,我想要提取blue meadows
。
我有我的所有介詞在一個文本文件。它工作正常,但我想在使用正則表達式中有一個問題。這裏是我的代碼: 進口重新使用ReGex來匹配表達式,Python
with open("Input.txt") as f:
words = "|".join(line.rstrip() for line in f)
pattern = re.compile('({})\s(\d+\w+|\w+)\s\w+'.format(words))
text3 = "003 canopy grace appt, classic royale garden, hennur main road, bangalore 43. near hennur police station"
print(pattern.search(text3).group())
這將返回:
AttributeError Traceback (most recent call last)
<ipython-input-83-be0cdffb436b> in <module>()
5 pattern = re.compile('({})\s(\d+\w+|\w+)\s\w+'.format(words))
6 text3 = ""
----> 7 print(pattern.search(text3).group())
AttributeError: 'NoneType' object has no attribute 'group
的主要問題是用正則表達式,我的預期成果是「hennur警察」即2個字後不久。在我的代碼中,我使用({})
與preps列表匹配,\s
後跟空格,(\d+\w+|\w+)
後跟單詞如19或hennur,\s\w+
後跟一個空格和一個單詞。我的正則表達式無法匹配,因此出現None
錯誤。 爲什麼它不起作用?
的Input.txt
文件的內容:
['near','nr','opp','opposite','behind','towards','above','off']
預期輸出:
hennur police
你需要檢查'words'中究竟是什麼。 –
適用於我(儘管你實際上應該接近'hennur警察'),所以你確實需要仔細檢查'Input.txt'是否正確(每行一個字)。 – Evert
input.txt的形式是['near','off','opposite'...]等等。我編輯了我的問題。覈實。 –