Python3 googletrans谷歌翻译出错:‘NoneType‘ object has no attribute ‘group‘

python googletrans ‘NoneType’ object has no attribute 'group’

示例代码:

from googletrans import Translator

service_urls = ['translate.google.cn', 'translate.google.com']
proxies = {'http': "localhost:80"}

def translate(text):
    translator = Translator(service_urls=['translate.google.cn'], proxies=proxies)
    trans_result = translator.translate(text, src='en', dest='zh-cn').text
    print(trans_result)
    return trans_result

if __name__ == '__main__':
    translate("中国人")

错误信息:

code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

经过分析,在gtoken.py定义的正则表达式没有找对对应的字符,search返回None,导致调用group(1)出现NoneType错误

    RE_TKK = re.compile(r'tkk:\'(.+?)\'', re.DOTALL)
    RE_RAWTKK = re.compile(r'tkk:\'(.+?)\'', re.DOTALL)
    ....
     # this will be the same as python code after stripping out a reserved word 'var'
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')

原理分析:

This issue re-emerged lately, (apparently) caused once again by some changes on the Google translation API.
Google翻译更改了API导致,googletrans版本为3.0.0,解析返回包失败,从以下两个方面解决该问题:
1、下载新版本googletrans 4.0.0+
2、通过其他的开源包替换(建议)

解决方法1

pip uninstall googletrans
pip install googletrans==4.0.0-rc1

解决方法2

pip install google_trans_new

from google_trans_new import google_translator  
translator = google_translator()  
translate_text = translator.translate('为中国人喝彩',lang_tgt='zh-CN')  
print(translate_text)

第三方包还有如下:
pip3 install py_translator==1.8.9

信息参考:https://stackoverflow.com/questions/52455774/googletrans-stopped-working-with-error-nonetype-object-has-no-attribute-group

你可能感兴趣的:(Python)