目標:我想創建一個提供兩個選項的英德詞典 1)在詞典中添加一個新詞 2)在詞典中搜索現有的翻譯
方法:為了這個想法,我使用了python中的字典函式,以英文單詞為Key,該單詞的德文翻譯為value。然后使用檔案句柄將其存盤在文本檔案中。
Quarry:這是我第一次嘗試在 Python 中處理檔案資料和字典,所以我
不確定這種編碼模式是否正確,因為我將在我的實際專案中使用這個想法。
以下代碼作業正常,但唯一的問題是,當我輸入新資料時,例如
在終端中:(1)添加新詞(2)查找翻譯...鍵入“完成”退出。-> 輸入選項:1 輸入英文單詞:one 輸入德文版本:eins ...接受多個輸入 ,資料保存如下: {'one': 'eins', 'two' : 'zwei', '三':'drei'...}
問題:現在,當我嘗試使用選項 2 時:輸入單詞以獲取德語翻譯:一個 -> 我得到以下輸出 在此處輸入影像描述
eng2ger = dict()
#Function:
def eng_ger_dict(f_name):
i = input("(1) Add new word\n(2) Look for the translation\n...Type 'done' to exit.\n->enter the option:")
x = 0
i = i.strip().lower()
if not i == 'done':
if i == 1 or 2:
inp = int(i)
#Option 1: Writting new word in dictionary
if inp == 1:
#input from user
eng = str(input("Enter english word: "))
ger = str(input("Enter german version: "))
#creating dictionary
eng2ger[eng] = ger
print(eng2ger, "\n")
#opening text file
f_write = open(f_name,"w")
line = str(eng2ger)
f_write.write(line)
eng_ger_dict(f_name)
#Option 2: Searching for the word
elif inp == 2:
f_read = open(f_name)
new_dict = dict()
new_dict = f_read
word = str(input("Enter the english word to get the german version of it: "))
for lines in new_dict:
lines = dict()
lines = lines
if lines.get(word) == -1:
continue
else:
#I also tried to get output from string slicing
# com_pos = lines.find(",")
# col_pos = lines.find(":")
# lines.split(com)
# pos = lines.find[new_word]
# print(new_word[pos : com_pos],"\n")
# eng_ger_dict("eng2ger.txt")
print(lines.get(word))
else:
print("German version of", word, "does not exist in dictionary,
'you can add new word by using 1st option :)\n")
eng_ger_dict("eng2ger.txt")
else:
print("Please select the option 1 or 2, else type done to exit\n")
else:
f_name.close()
exit()
#Function call:
eng_ger_dict("eng2ger.txt")
uj5u.com熱心網友回復:
問題似乎分為兩部分:
- 搜索一個詞。
- 添加一個詞。
搜索一個專案是dict相對簡單的,像這樣:
d = {'one': 'eins', 'two' : 'zwei', 'three' : 'drei'}
word = 'one'
if word in d.keys():
print('the word is here')
添加一個詞是這樣完成的:
d = {'one': 'eins', 'two' : 'zwei', 'three' : 'drei'}
new_word_english = 'four'
new_word_german = 'vier'
d['four'] = 'vier'
這給出了這個:
{'one': 'eins', 'two': 'zwei', 'three': 'drei', 'four': 'vier'}
您必須相應地將上述兩個實作到例程中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522823.html
