在Python中使用Regex查找数字并将数字附加到字符串

时间:2019-02-18 20:17:21

标签: python regex dictionary for-loop

我正在尝试查找输入字符串中的任何数字,然后在字符串的末尾附加每个数字的英文单词。 但是,我的代码抛出错误can't assign to function call

import re

def to_eng(s):

    words = {"0":"zero","1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"}
    k = re.findall(r"[0-9]",s)
    for i in k:
        w = words.items(), key=lambda x: x[0]
    print(s + w)

s = "I want to buy 17 cars."
to_eng(s)

我希望输出为:I want to buy 17 cars. one seven

2 个答案:

答案 0 :(得分:1)

提示:这里缺少一些东西(也许是函数调用?)

for i in k:
    w = words.items(), key=lambda x: x[0]
    #  ^                                 ^
print(s + w)

但是您可以将其更改为:

def to_eng(s):
    words = {"0":"zero","1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"}
    rx = re.compile(r'\d')
    for m in rx.finditer(s):
        s = s + " " + words[m.group(0)]
    print(s)

屈服

I want to buy 17 cars. one seven


或者-甚至更好-一起使用列表:

def to_eng(s):
    words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
    rx = re.compile(r'\d')

    return s + " ".join(words[int(m.group(0))] for m in rx.finditer(s))


至于最后一个问题-用英文单词插入方括号-您需要组成替换函数:

def to_eng(s):
    words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
    rx = re.compile(r'\d+')

    def repl(digits):
        return digits.group(0) + " (" + " ".join(words[int(x)] for x in digits.group(0)) + ")"

    return rx.sub(repl, s)

这将产生示例字符串:

I want to buy 17 (one seven) cars.

答案 1 :(得分:0)

我将按照以下方式进行操作:

import re
s = "I want to buy 17 cars."
words = {"0":"zero","1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"}
k = re.findall(r"[0-9]",s)
w = ' '.join([words[i] for i in k])
print(w) #one seven

此解决方案使用所谓的list理解,与使用for循环相比,此方法可以提供更简洁的代码。