我正在尝试查找输入字符串中的任何数字,然后在字符串的末尾附加每个数字的英文单词。
但是,我的代码抛出错误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
答案 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
循环相比,此方法可以提供更简洁的代码。