编写一个以整数作为输入参数并返回的函数 使用单词的整数。例如,如果输入是4721那么 函数应该返回字符串"四个七二一"。注意 这些单词之间应该只有一个空格,它们应该是 所有在你返回的字符串中小写。
这是我的代码:
def Numbers_To_Words (number):
dict = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 0: "zero"}
output_str = " "
list = []
#Main Program
number = 4721
result = Numbers_To_Words (number)
print (result)
我的问题是,如何将数字分开,然后与我创建的字典进行比较?我知道长度不适用于整数数据类型。我知道将密钥发送到字典并获取其各自值的进一步逻辑。但在此之前,我被困在这里分隔整数的数字。
答案 0 :(得分:5)
使用模块: https://pypi.python.org/pypi/num2words
另外,请检查类似的问题:How do I tell Python to convert integers into words
您可以安装模块,看看它是如何在那里实现的。
但你的问题解决了:
def Numbers_To_Words (number):
dictionary = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
'7': "seven", '8': "eight", '9': "nine", '0': "zero"}
return " ".join(map(lambda x: dictionary[x], str(number)))
print Numbers_To_Words(1234)
答案 1 :(得分:5)
有一种比其他方式更简单的方法:
def number_to_words(number)
words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
return " ".join(words[int(i)] for i in str(number))
答案 2 :(得分:1)
def number_to_words(number):
dict={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","0":"zero"}
s=""
for c in str(number):
s+=dict[c]+" "
#if it's matter that the string won't conatain
#space at the end then add the next line:
s=s[:-1]
return s
答案 3 :(得分:0)
我会使用re.sub
>>> def Numbers_To_Words (number):
dict_ = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six", '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
return re.sub(r'\d', lambda m: dict_[m.group()] + ' ', str(number)).strip()
>>> print Numbers_To_Words(4721)
four seven two one
>>> print Numbers_To_Words(98765423)
nine eight seven six five four two three
答案 4 :(得分:0)
def number_to_words(number):
names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
lst = []
while True:
lst.insert(0, number % 10) # Prepend
number /= 10
if number == 0: # Do this here rather than in the while condition
break; # so that 0 results in ["zero"]
# If you want a list, then:
return lst;
# If you want a string, then:
return " ".join(lst)
答案 5 :(得分:0)
这将帮助您在无法导入用于将数字转换为单词的模块的地方。该代码用于将数字从1转换为1000(包括两个数字)。
["sea", # User's search term
["sears", # Suggested search terms
"search engines",
"search engine",
"search",
"sears.com",
"seattle times"],
["7,390,000 results", # Suggested search descriptions
"17,900,000 results",
"25,700,000 results",
"1,220,000,000 results",
"1 result",
"17,600,000 results"],
["http://example.com?q=sears", # Links for suggested searches (optional)
"http://example.com?q=search+engines",
"http://example.com?q=search+engine",
"http://example.com?q=search",
"http://example.com?q=sears.com",
"http://example.com?q=seattle+times"]]