2 回答
TA贡献1802条经验 获得超5个赞
如果我理解正确,您想在文本中找到用单词写的数字lyrics
。由于 RegEx 无法理解一个单词,因此您需要先解决该问题。为此,您可以:
创建从单词到数字的映射
在文本上应用映射
在新文本上使用正则表达式,以获取数字
样本
import re
# mapping
word_digit_map = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
}
lyrics = '''Twelve drummers drumming, eleven pipers piping
Ten lords a leaping, nine ladies dancing, eight maids a milking
Seven swans a swimming, six geese a laying, five gold rings
Four calling birds, three French hens
Two turtle doves and a partridge in a pear tree
'''
# apply mapping
for word in word_digit_map.keys():
lyrics = lyrics.lower().replace(word, str(word_digit_map[word]))
# Use regex
xmasReExp = re.compile(r'\d+')
print(xmasReExp.findall(lyrics))
出去
['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2']
添加回答
举报