简体   繁体   中英

Find Digit and Append Number Word to String Using Regex in Python

I am trying to find any digits an input string and then append the English word for each digit at the end of the string. However, my code is throwing an error 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 would like my output to be: I want to buy 17 cars. one seven I want to buy 17 cars. one seven

Hint: there's missing something here (maybe a function call?)

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

But you could change it to:

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)

Yielding

I want to buy 17 cars. one seven


Or - even better - use a list altogether:

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


As for your last question - inserting brackets with the english words - you need to make up a replacement function:

 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) 

This yields for your example string:

 I want to buy 17 (one seven) cars. 

I would do it following way:

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

This solution use so called list comprehension, this allow more concise code than using for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM