2014-02-27 52 views
1

我有很多句子,但是我會創建一個函數來分別對每個句子進行操作。所以輸入只是一個字符串。我的主要目標是提取在"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 
+0

你需要檢查'words'中究竟是什麼。 –

+0

適用於我(儘管你實際上應該接近'hennur警察'),所以你確實需要仔細檢查'Input.txt'是否正確(每行一個字)。 – Evert

+0

input.txt的形式是['near','off','opposite'...]等等。我編輯了我的問題。覈實。 –

回答

1

該文件包含Python列表文字。使用ast.literal解析文字。

>>> import ast 
>>> ast.literal_eval("['near','nr','opp','opposite','behind','towards','above','off']") 
['near', 'nr', 'opp', 'opposite', 'behind', 'towards', 'above', 'off'] 

import ast 
import re 

with open("Input.txt") as f: 
    words = '|'.join(ast.literal_eval(f.read())) 
    pattern = re.compile('(?:{})\s(\d*\w+\s\w+)'.format(words)) 
    text3 = "003 canopy grace appt, classic royale garden, hennur main road, bangalore 43. near hennur police station" 

    # If there could be multiple matches, use `findall` or `finditer` 
    # `findall` returns a list of list if there's capturing group instead of 
    # entire matched string. 
    for place in pattern.findall(text3): 
     print(place) 

    # If you want to get only the first match, use `search`. 
    # You need to use `group(1)` to get only group 1. 
    print pattern.search(text3).group(1) 

輸出(第一行是for環印刷,第二個來自search(..).group(1)):

hennur police 
hennur police 

注意需要re.escape每個字,如果有正則表達式中具有特殊含義的單詞中的任何特殊字符。

+0

它的工作.. thanx @falsetru –

+1

@劍,修改你的問題一點點來說清楚。 – falsetru