用户输入转换为OTAN语音字母的单词。
我必须使用字典,我把这段代码:
def otan():
dictionary = {'A':'Alpha', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'I':'India', 'J':'Juliet', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey', 'X':'Xray', 'Y':'Yankee', 'Z':'Zulu'}
input('Enter a word:')
otan()
我输入一个单词例如GH
但是出现了这个:NameError: name 'GH' is not defined
我不理解错误,因为字典包含字母G和H
答案 0 :(得分:0)
你是说这个?
def otan(word):
dictionary = {'A':'Alpha', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'I':'India', 'J':'Juliet', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey', 'X':'Xray', 'Y':'Yankee', 'Z':'Zulu'}
phon = [dictionary[w] for w in word]
return ' '.join(phon)
word = raw_input('Enter word: ')
print otan(word)
顺便说一句。如果您想在GH
中输入单词dictionary
,则不会H
答案 1 :(得分:0)
您需要单独访问每个密钥并使用raw_input
,GH将是两个密钥而不是一个
dictionary = {'A':'Alpha', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf',"H":"Hotel", 'I':'India', 'J':'Juliet', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey', 'X':'Xray', 'Y':'Yankee', 'Z':'Zulu'}
inp = raw_input('Enter a word:')
print(" ".join(map(dictionary.get,inp)))
Enter a word:GH
Golf Hotel
答案 2 :(得分:-2)
您使用的是Python2,因此需要使用raw_input('Enter word:')
。
接下来,当您从用户那里得到这个词时,您需要为每个字母获取,这是您字典中的相应字词:
d = {'A':'Alpha', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'I':'India', 'J':'Juliet', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey', 'X':'X-ray', 'Y':'Yankee', 'Z':'Zulu'}
word = raw_input('Enter word:')
for letter in word:
print(d.get(letter.upper()), end='')
编写相同循环的更简单方法是:
word = raw_input('Enter word:')
print(' '.join(d.get(letter.upper(), letter) for letter in word))
以下是一个示例运行:
>>> word = raw_input('Enter word:')
Enter word:PYTHON
>>> print(' '.join(d.get(letter.upper(), letter) for letter in word))
Papa Yankee Tango H Oscar November
原始词典中缺少H
,这就是它原样显示的原因。