我的目的是找出文档中所有与年龄相关的单词。举个例子,在句子“她二十二岁。她爱你。你永远不会知道这让我多么忧郁”,我想找二十二岁。但是regex.finditer总是返回20而不是22。
enter code here
regex_list = {}
regex_list['before_age'] = (r'age|aged|he\s*is|she\s*is|she\'s|he\'s')
regex_list["nums_as_words"] = (r'two|twenty|twenty-two')
p = r'(?i)(({before_age})\s*[a\s|an\s]?\s*({number_words}))'.format(
before_age = regex_list['before_age'],
number_words = regex_list["nums_as_words"]
)
text = "She's twenty-two. And she's loving you. And you'll never know how it makes me blue"
for match in regex.finditer(p, str(text)):
if match.group(3):
print (match.group(3)) 回报率:20
发布于 2020-04-30 06:15:16
正则表达式的顺序很重要。
试一试
regex_list["nums_as_words"] = (r'two|twenty-two|twenty')因为二十在二十二之内,所以它总是先找到它。
https://stackoverflow.com/questions/61512654
复制相似问题