Python - google-trans-new 在正常工作的代码上抛出错误

Python - google-trans-new throwing error on code that was working

我一直在使用 Google 翻译 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 的错误,该错误已知且已更正。 (查看 this 讨论以获取更多信息)。

具有错误修复的模块的新版本尚未发布到 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

检查 Python 转换器代码的这 2 个备选方案:

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