[英]French Dictionary on Python
本質上,我希望代碼執行的操作是讓用戶輸入一個單詞。 然后,該代碼將搜索字典(French_Dictionary),嘗試查找該單詞,如果成功,則打印該單詞的翻譯。
我是python的初學者,我只是想知道是否有人可以幫助我至少理解編寫這些步驟所需的概念。
到目前為止,這是我的代碼(基本上只是形式)
def opening_statement():
print "Welcome to a French Dictionary"
while True:
print "Choose [1] (English to French) or [2] (French to English) "
choice = input("Enter 1 or 2 ")
if choice == 1:
print "You have selected the English to French Dictionary"
break
elif choice == 2:
print "You have selected the French to English Dictionary"
break
else:
print "n/a"
def secondary_statement():
while True:
word = raw_input("Type your word: ")
word = word.lower()
print 'Please confirm - Your word is "%s"' % (word)
answer= input("Yes [1] or No [2] ")
if answer == 1:
print "Translating..."
break
elif answer == 2:
print "Repeating process..."
else:
print "n/a"
#Will add more and more words manually to dictionary
French_Dictionary = {
"aller" : "to go",
"avoir" : "to have"
}
print opening_statement()
print secondary_statement()
為了給您高層次的想法:
您將英語單詞用作翻譯詞典中的鍵來獲取單詞的法語版本:
>>> dictionary_of_words = {"yes":"oui", "no":"non"}
>>> dictionary_of_words["yes"]
'oui'
>>>
因此,當您讀取一個單詞作為輸入時,請檢查該單詞是否包含在字典的鍵列表中,如果包含,則打印翻譯,否則拋出異常。 要遍歷字典,遍歷鍵也可以:
>>> list_keys = dictionary_of_words.keys()
>>> list_keys
['yes', 'no']
>>> for i in list_keys:
... print dictionary_of_words[i]
...
oui
non
>>>
我很感謝您為字典使用字典數據結構; 如果您要同時翻譯這兩種方法,那么也許更合適的是不同的數據結構? 像2列表一樣,您可以在其中通過索引或其他內容鏈接它們?
from functools import partial
eng = ["yes", "no"]
fr = ["oui", "non"]
def freng(fr, eng, mot):
return eng[fr.index(mot)]
def engfr(fr, eng, word):
return fr[eng.index(word)]
freng = partial(freng, fr, eng)
engfr = partial(engfr, fr, eng)
局部函數簡化了調用簽名,因此您只需擁有freng(“ oui”)並返回“ yes”即可。
注意在字典中沒有單詞的情況下的處理。 就目前而言,這將引發異常。 您可能需要更優雅地處理。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.