显示空列表时出现正则表达式错误,尽管字符串中存在该模式

2024-09-27 23:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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))

Tags: importrelyricsninetenpipingtwelveeleven
2条回答

结果是正确的,即空列表\d表示数字,而lyrics中没有匹配的模式

如果我理解正确,您希望查找文本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))

Out

['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2']

相关问题 更多 >

    热门问题