问题
The user enter a word that which is converted to OTAN phonetic alphabet.
I have to use a dictionary and I put this code:
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()
I enter a word for exemple GH
But appears this : NameError: name 'GH' is not defined
I dont understand the error because the dictionary includes the letter G and H
回答1:
You need to access each keys separately and use raw_input
, GH would be two keys not one
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:
You mean this?
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)
BTW. If you want to enter word GH
in your dictionary
there is no H
回答3:
You are using Python2, so you need to use raw_input('Enter word:')
.
Next, when you get the word from the user, you need to fetch for each letter, the corresponding word from your dictionary:
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='')
A simpler way to write the same loop is:
word = raw_input('Enter word:')
print(' '.join(d.get(letter.upper(), letter) for letter in word))
Here is a sample run:
>>> 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
You are missing H
in your original dictionary, which is why it is showing as is.
来源:https://stackoverflow.com/questions/26324038/dictionary-that-covert-a-string-to-otan-phonetic-alphabet