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

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值