Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用正则表达式查找数字并将数字字附加到字符串_Python_Regex_Dictionary_For Loop - Fatal编程技术网

在Python中使用正则表达式查找数字并将数字字附加到字符串

在Python中使用正则表达式查找数字并将数字字附加到字符串,python,regex,dictionary,for-loop,Python,Regex,Dictionary,For Loop,我试图找到输入字符串中的任何数字,然后在字符串末尾为每个数字添加英文单词。 但是,我的代码抛出了一个无法分配给函数调用的错误 我希望我的产出是:我想买17辆车。一七提示:这里缺少一些东西,可能是函数调用 for i in k: w = words.items(), key=lambda x: x[0] # ^ ^ print(s + w) 但您可以将其更改为: def to_eng(s): words =

我试图找到输入字符串中的任何数字,然后在字符串末尾为每个数字添加英文单词。 但是,我的代码抛出了一个无法分配给函数调用的错误


我希望我的产出是:我想买17辆车。一七提示:这里缺少一些东西,可能是函数调用

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.

我会这样做:

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

这个解决方案使用了所谓的列表理解,这使得代码比for循环更简洁。

@whiteyflowr:查看底部的更新答案,如果它对您有帮助,请接受答案。
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