python GEB.py
会产生一系列毫无意义的英文句子,例如:
resurgent inaesthetic cost. the bryophytic fingernail. aversive fortieth peach. the asterismal hide. the flour who translate gown which take_a_dare a punch through applewood whom the renewed request enfeoff. an lobeliaceous freighter beside tuna.
并将它们保存到gibberish.txt中。这个脚本运行得很好。另一个脚本(
translator.py
)通过py-googletrans Python模块尝试将那些随机的句子翻译成葡萄牙语。from googletrans import Translator
import json
tradutor = Translator()
with open('data.json') as dataFile:
data = json.load(dataFile)
def buscaLocal(keyword):
if keyword in data:
print(keyword + data[keyword])
else:
buscaAPI(keyword)
def buscaAPI(keyword):
result = tradutor.translate(keyword, dest="pt")
data.update({keyword: result.text})
with open('data.json', 'w') as fp:
json.dump(data, fp)
print(keyword + result.text)
keyword = open('/home/user/gibberish.txt', 'r').readline()
buscaLocal(keyword)
目前第二个脚本只输出 gibberish.txt 中第一句话的乱码翻译,类似于:
复苏的不美观成本。 aumento de custos inestético.
我尝试使用 readlines() 而不是 readline(),但是我遇到了以下错误:
Traceback (most recent call last):
File "main.py", line 28, in <module>
buscaLocal(keyword)
File "main.py", line 11, in buscaLocal
if keyword in data:
TypeError: unhashable type: 'list'
我已经阅读了关于这个错误的类似问题,但是我不清楚应该使用什么来读取包含在gibberish.txt中的整个句子列表(新句子在新行开头)。
如何读取包含在gibberish.txt中的整个句子列表? 我应该如何修改translator.py中的代码才能实现这一点? 如果必要的话,我可以编辑问题,我是一个Python新手,如果有人能帮助我,我会非常感激。
readlines
导致了这个错误。相反,readlines
返回一个行的列表,您可能正在尝试将该列表放入一个dict
中,但是您不能这样做,因为列表对象不可哈希。一般来说,您需要提供一个 [mcve]。 - juanpa.arrivillagadata.update({keyword: result.text})
- juanpa.arrivillagareadlines
返回一个list
对象,它不可哈希,因此不能用作dict
对象的键。 - juanpa.arrivillaga