Python翻译:我想翻译句子中的多个单词

Python翻译:我想翻译句子中的多个单词,python,translate,Python,Translate,所以我开始做这个小翻译程序,用输入把英语翻译成德语。然而,当我输入多个单词时,我会得到我输入的单词,然后是正确的翻译 这就是我到目前为止所做的: data = [input()] dictionary = {'i':'ich', 'am':'bin', 'a':'ein', 'student':'schueler', 'of the':'der', 'german':'deutschen', 'language': 'sprache'} from itertools import tak

所以我开始做这个小翻译程序,用输入把英语翻译成德语。然而,当我输入多个单词时,我会得到我输入的单词,然后是正确的翻译

这就是我到目前为止所做的:

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':'der'
。出于演示目的,我选择保留一个键长度为1的字典,因此上面的key:value对变成了
'of':'der'
,这是不正确的,因为德语语法比这稍微复杂一些


你现在有更多的问题比你开始,这是玩具项目的目的。如果我是你,我会研究开源项目是如何处理这种情况的,并尝试找出合适的方法。祝您的项目好运。

我注意到您的
输入中有两件事。首先,您可以将两个单词翻译成一个(在
字典中有两个单词
关键字
),另一件事是
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
例如,如果您有一个3个单词的
,此操作也会失败,但如果您最多只有两个单词,则应该可以

ich bin ein schueler der deutschen sprache