[英]Python translator: I want to translate multiple words in sentence
因此,我開始着手開發這個小小的翻譯程序,該程序可以通過輸入將英語翻譯成德語。 但是,當我輸入多個單詞時,我得到的是輸入的單詞,然后是正確的翻譯。
這是我到目前為止的內容:
data = [input()]
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of
the':'der', 'german':'deutschen', 'language': 'sprache'}
from itertools import takewhile
def find_suffix(s):
return ''.join(takewhile(str.isalpha, s[::-1]))[::-1]
for d in data:
sfx = find_suffix(d)
print (d.replace(sfx, dictionary.get(sfx, sfx)))
我正在嘗試獲得以下輸出:
"i am a student of the german sprache"
相對於:
"ich bin ein schueler der deutschen spracher"
我對python很陌生,所以任何幫助將不勝感激
data = [input()]
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of the':'der', 'german':'deutschen', 'language': 'sprache'}
for word in data:
if word in dictionary:
print dictionary[word],
說明:
對於輸入中的每個單詞,如果該單詞在詞典中存在,它將打印與該單詞關聯的值,並且逗號(,)將跳過換行符。
將代碼更改為此應該提供您要尋找的第一步。
data = raw_input()
dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of':'der', 'german':'deutschen', 'language': 'sprache'}
from itertools import takewhile
def find_suffix(s):
return ''.join(takewhile(str.isalpha, s[::-1]))[::-1]
for d in data.split():
sfx = find_suffix(d)
print (d.replace(sfx, dictionary.get(sfx,''))),
您現在擁有的內容不會考慮每個單獨的單詞,因為數據不是您想要的單詞列表,而是一個包含一個字符串(您提供的輸入)的列表。 嘗試對您的代碼段進行打印調試,以了解我在說什么。
請注意,在您的項目中出現這種邏輯情況時會出現情況。 接受每個單詞並將其與德語對應單詞進行翻譯會禁止字典條目超過1個單詞,例如'of the':'der'
。 出於演示目的,我選擇保留長度為1的鍵的字典,因此上述key:value對變為'of':'der'
,這是不正確的,因為德語語法比這復雜得多。
您現在遇到的問題比開始時要解決的更多,這正是玩具項目的目的。 如果我是你,我將研究開源項目如何處理此類情況,並嘗試找到合適的解決方案。 祝您項目順利。
我注意到您的input
有兩件事。 第一件事是您可以將兩個單詞翻譯成一個單詞( dictionary
兩個單詞key
),另一件事是input
可以包含不應翻譯的德語單詞。 考慮到這兩個條件,我認為最好的方法是split()
input
並loop
檢查單詞。 請遵循以下代碼中的注釋:
dictionary = {'i': 'ich', 'am': 'bin', 'a': 'ein', 'student': 'schueler', 'of the': 'der', 'german': 'deutschen', 'language': 'sprache'}
data = "i am a student of the german sprache"
lst = data.split()
result = ''
i = 0
while i < len(lst):
# try/except to see if the key is one word or two words
try:
if lst[i] in dictionary.values(): # Check if the word is german
result += lst[i] + ' '
i += 1
else:
result += dictionary[lst[i]] + ' ' # get the word from the dictionary
i += 1
except KeyError:
result += dictionary[lst[i] + ' ' + lst[i+1]] + ' ' # if the word is not german and not in dictionary, add the 2nd word and get from dictionary
i += 2
print result
輸出:
ich bin ein schueler der deutschen sprache
例如,如果您有3個單詞的key
,這也會失敗,但是如果您最多只有2個單詞,那應該沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.