首页 > 解决方案 > 如何使用字典在 Python 中将荷兰语翻译成英语

问题描述

我正在尝试使用此代码翻译我是 Jason,但是当我使用它时,它什么也没打印,除非我做一个像 hello 这样的词,然后它会打印出 Guten 标签,仅此而已。另外,我无法将输入数据转换为小写,以便将其与字典进行比较。我该怎么做才能使此代码正常工作?

name = input("Please enter your name\n")
data = [input("Please enter sentence\n")]
data = data.lower() #to make sentence lowercase to be able to compare it to the words in the dictionary
dictionary = {"hello": "hallo", "i" : "ik", "am" : "ben"}

dictionary[name] = name
for word in data:
    if word in dictionary:
        print (dictionary[word],)

这是回溯

*请输入你的名字

杰森

请输入句子

我是杰森*

Traceback (most recent call last):
  File "C:/Users...", line 3, in <module>
    data = data.lower()
AttributeError: 'list' object has no attribute 'lower'

标签: pythonmachine-translation

解决方案


您根据用户的回复列出了一份清单

In [26]: data = [input("Please enter sentence\n")]

Please enter sentence
You are Jason

In [27]: data
Out[27]: ['You are Jason']

列表没有lower方法。
首先获取用户的响应并将其转换为小写。

In [28]: data = input("Please enter sentence\n")

Please enter sentence
You are Jason

In [29]: data
Out[29]: 'You are Jason'

In [30]: data = data.lower()

In [31]: data
Out[31]: 'you are jason'

然后在空格上拆分字符串以获取单个单词的列表。

In [32]: data = data.split()

In [33]: data
Out[33]: ['you', 'are', 'jason']

推荐阅读