我有很多句子,尽管我会创建一个可以单独对每个句子进行操作的函数。所以输入只是一个字符串。我的主要目标是提取介词后面的单词,例如“near blue meadows”
,我希望提取blue meadows
。
我将所有介词都保存在一个文本文件中。它工作正常,但我猜使用的正则表达式有问题。这是我的代码:
导入重新
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 Police”,即near之后的2个单词。在我的代码中,我使用 ({})
从准备列表中进行匹配, \s
后跟空格, (\d+\w+|\w+)
后跟诸如 19th 或 hennur 之类的单词, \s\w+
后跟一个空格和一个单词。我的正则表达式无法匹配,因此出现 None
错误。
为什么不起作用?
Input.txt
文件的内容:
['near','nr','opp','opposite','behind','towards','above','off']
预期输出:
hennur police
最佳答案
该文件包含 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
每个单词中是否存在在正则表达式中具有特殊含义的特殊字符。
关于python - 使用 ReGex 、Python 匹配表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061087/