简体   繁体   English

如何根据字典将数字转换为单词?

[英]How to convert a number into words based on a dictionary?

First, the user inputs a number.首先,用户输入一个数字。 Then I want to print a word for each digit in the number.然后我想为数字中的每个数字打印一个单词。 Which word is determined by a dictionary.哪个词是由字典决定的。 When a digit is not in the dictionary, then I want the program to print ".".当数字不在字典中时,我希望程序打印“.”。

Here is an example of how the code should work:这是代码应如何工作的示例:

Enter numbers : 12345
Result: one two three ! !

Because 4 and 5 are not in Exist our dictionary, the program has to print "!"因为 4 和 5不在我们的字典中,所以程序必须打印“!” . .

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for i,j in DictN.items():
    for numb in InpN:
        if numb in i:
            print(j)
        else:
            print('!')

MY WRONG OUTPUT我错了 OUTPUT

one
!
!
!
!
two
!
!
!
!
three
!

Process finished with exit code 0
# Consider the input as an int
indata = input('Enter Ur Number: ')

for x in indata: print(DictN.get(x,'!'))

a dict works like this: dict是这样工作的:

# the alphabetical letters are the keys, and the numbers are the values which belong to the keys
a = {'a': 1, 'b': 2}

# if you want to have value from a it would be 
print(a.get('a'))
# or
print(a['a'])

# which is in your example:
DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')
print(DictN[InpN])

in your example you could do something like this在你的例子中你可以做这样的事情

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')
for i in InpN:
  print(InpN[i], '!')

by the way you would not use these variable names in Python. This source is good for best practices: https://peps.python.org/pep-0008/ https://python-reference.readthedocs.io/en/latest/docs/dict/get.html顺便说一句,您不会在 Python 中使用这些变量名称。此来源适用于最佳实践: https://peps.python.org/pep-0008/ https://python-reference.readthedocs.io/en/latest /docs/dict/get.html

The solution to your problem can be programmed pretty much exactly how it's written in english, like this:您的问题的解决方案几乎可以完全按照英文编写的方式进行编程,如下所示:

DictN = {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for i in InpN:
    if i in DictN:
        print(DictN[i])
    else:
        print("!")

gerrel93 explained how to retrieve data from a dictionary, and for many methods regarding iterables (objects such as strings and lists), dictionaries are treated as a list of their keys. gerrel93解释了如何从字典中检索数据,对于许多与可迭代对象(字符串和列表等对象)有关的方法,字典被视为其键的列表。 The in keyword is one example of this. in关键字就是其中一个例子。

Since the other answers already show you how to use a dictionary, thought I'd demonstrate an alternative way of solving your problem.由于其他答案已经向您展示了如何使用字典,我想我会展示另一种解决问题的方法。 Would have written this as a comment, but I don't have enough reputation:)会把它写成评论,但我没有足够的声誉:)

The hope is that this helps you learn about iterators and some neat builtins希望这可以帮助您了解迭代器和一些简洁的内置函数

inp = input("Enter Ur Number: ")

words = ["one", "two", "three"]
dict_n = dict(zip(range(1, len(words) + 1), words))
print(" ".join([dict_n.get(int(n), "!") for n in inp]))

Breaking it down打破它

>>> range(1, len(words)) # iterator
range(1, 3)

>>> dict(zip([1,2,3], [4,5,6])) # eg: zip elements of two iterators
{1: 4, 2: 5, 3: 6}

>>> dict(zip(range(1, len(words)), words))
{1: 'one', 2: 'two'}

>>> [n for n in range(3)] # list comprehension
[0, 1, 2]

>>> " ".join(["1", "2", "3"])
'1 2 3'

Hope the above block helps break it down:)希望上面的块有助于分解它:)

The problem with your code is that you loop over the dictionary, and then check whether a certain value is in the input.您的代码的问题是您遍历字典,然后检查输入中是否有某个值。 You should do this in the reverse way: Loop over the input and then check whether aech digit is in the dictionary:您应该以相反的方式执行此操作:循环输入,然后检查 aech 数字是否在字典中:

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for digit in InpN:
    if digit in DictN:
        print(DictN[digit], end=" ")
    else:
        print("!", end=" ")
print("")

The output is the following: output 如下:

Enter Ur Number: 12345
one two three ! ! 

So, first we define the dictionary DicN and receive the input in InpN exactly as you did.因此,首先我们定义字典DicN并像您一样在InpN中接收输入。 Then we loop over the string we received as input.然后我们遍历我们收到的作为输入的字符串。 We do this because we want to print a single character for each digit.我们这样做是因为我们想为每个数字打印一个字符。 In the loop, we check for each digit whether it is in the dictionary.在循环中,我们检查每个数字是否在字典中。 If it is, then we retreive the correct word from the dictionary.如果是,那么我们从字典中检索正确的单词。 If it isn't, then we print !如果不是,那么我们打印! . .

Do also note that I used end=" " in the prints.另请注意,我在印刷品中使用了end=" " This is because otherwise every word or !这是因为否则每个字或! would be printed on a new line.将打印在一个新行上。 The end argument of the print function determines what value is added after the printed string. print function 的end参数确定在打印的字符串之后添加什么值。 By default this is "\n" , a newline.默认情况下这是"\n" ,换行符。 That's why I changed it to a space.这就是我将其更改为空格的原因。 But this does also mean that we have to place print() after the code, because otherwise the following print call would print its text on the same line.但这也意味着我们必须将print()放在代码之后,否则接下来的print调用将在同一行打印其文本。

Alternative using map :替代使用map

DictN={'1':'one','2':'two','3':'three'}
print(*map(lambda i:DictN.get(i,'!'),input('Enter Ur Number: ')),sep=' ')

# Enter Ur Number: 12345
# one two three ! !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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