猿问

尽管歌词字符串中存在模式,但正则表达式错误显示一个空列表

import re

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

'''

xmasReExp = re.compile(r'\d+\s\w+')

print(xmasReExp.findall(lyrics))


拉风的咖菲猫
浏览 125回答 2
2回答

12345678_0001

如果我理解正确,您想在文本中找到用单词写的数字lyrics。由于 RegEx 无法理解一个单词,因此您需要先解决该问题。为此,您可以:创建从单词到数字的映射在文本上应用映射在新文本上使用正则表达式,以获取数字样本import re# mappingword_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 pipingTen lords a leaping, nine ladies dancing, eight maids a milkingSeven swans a swimming, six geese a laying, five gold ringsFour calling birds, three French hensTwo turtle doves and a partridge in a pear tree'''# apply mappingfor word in word_digit_map.keys():    lyrics = lyrics.lower().replace(word, str(word_digit_map[word]))# Use regexxmasReExp = re.compile(r'\d+')print(xmasReExp.findall(lyrics))出去['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2']

呼如林

结果是正确的,即一个空列表。\d表示数字,并且您在lyrics.
随时随地看视频慕课网APP

相关分类

Python
我要回答