我一直在使用Google Translate API自动翻译几个单词,这已经运行了几个月,但2-3天前我开始遇到问题,因为这个片段引发了一个错误。
代码:
from google_trans_new import google_translator
translator = google_translator()
print(status) #light rain
translate_text = translator.translate(status, lang_tgt='pt')
print(translate_text) #chuva leve
错误
File "bot.py", line 74, in checkBadConditions
translate_text = translator.translate(status, lang_tgt='pt')
File "/home/pi/.local/lib/python3.7/site-packages/google_trans_new/google_trans_new.py", line 188, in translate
raise e
File "/home/pi/.local/lib/python3.7/site-packages/google_trans_new/google_trans_new.py", line 152, in translate
response = json.loads(response)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 358 (char 357)
我也尝试过translate_text = translator.translate(status, lang_src='en', lang_tgt='pt')
,但也不起作用
有什么更新吗?我做错了什么
这似乎是来自已知且已损坏的包google-trans-new
的错误。(有关详细信息,请查看此讨论(。
带有错误修复程序的模块的新版本尚未向pip发布。因此,您必须手动进行修改或等待newt版本发布。
from bs4 import BeautifulSoup
from bs4.formatter import HTMLFormatter
from googletrans import Translator
import requests
translator = Translator()
class UnsortedAttributes(HTMLFormatter):
def attributes(self, tag):
for k, v in tag.attrs.items():
yield k, v
检查这2个Python转换器代码的替代方案:
https://neculaifantanaru.com/en/python-code-text-google-translate-website-translation-beautifulsoup-library.html
或此处:
https://neculaifantanaru.com/en/example-google-translate-api-key-python-code-beautifulsoup.html