如何在字典菜单中选择单词?



我正在使用python 2编写英语词典。我创建了一个字典。例如,字典键中的"家"和"马"。如果用户输入"ho","home"和"horse"就会来。我把这些放在底线。但是当用户选择单词 1 时,我想调用我首先设置的字典中的键和值。我该怎么做?

myEngDict = {"horse": "The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus","home": "the place where one lives permanently, especially as a member of a family or household."}
def Words():
word_List = []
count = 0
search_words = raw_input("Please enter a search term: ")
for i in myEngDict.keys():
if i.startswith(search_words):
count+=1
word_List.append(i)
print "{}{}{}".format(count,".", i)
else:
pass
choose = input("Which one?")

例如,如果首先出现"家",则用户选择 1:

节目显示:

home: the place where one lives permanently, especially as a member of a family or household.

首先,您应该在最后一行中使用raw_input。然后,您需要查找word_List中提供的。

while True:
try:
choose = int(raw_input("Which one?"))
# Keep the key as a separate variable for faster reference
key = word_List[choose - 1]
# Use labels with the format function. It's easier to read and understand
print '{label}: {text}'.format(label=key, text=myEngDict[key])
# Be sure to have a break or return on success.
return
except ValueError: 
# If someone provides 'cat', it will raise an error.
# Inform the user and go back to the start.
print 'Please provide an integer'
except IndexError:
# The user has provided a value above the length of word_List or 
# less than one. Again, inform the user and go back to start.
print 'You must enter a number between 1 and {c}'.format(c=len(word_List))

通过不更改太多代码,您只需在函数中以相同的缩choose添加 print 语句:

print ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))

最新更新