[英]How to choose the word in the dictionary menu?
我正在使用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
提供的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 ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.