Python使用googletrans包进行翻译-AttributeError: ‘NoneType‘ object has no attribute ‘group‘&httpcore._ex
Posted ZSYL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python使用googletrans包进行翻译-AttributeError: ‘NoneType‘ object has no attribute ‘group‘&httpcore._ex相关的知识,希望对你有一定的参考价值。
问题分析
安装googletrans包:
pip install googletrans
默认版本是:3.0.0
第一个报错:httpcore._exceptions.ConnectTimeout: timed out
连接超时!
因为是外网googletrans默认访问URL是translate.google.com
,所以修改URL:
# 导入google翻译接口工具
from googletrans import Translator
# 实例化翻译对象
translator = Translator(service_urls=['translate.google.cn'])
translator = Translator(service_urls=['translate.google.cn'])
第二个报错:
>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.translate('안녕하세요.')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
translator.translate('안녕하세요.')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate
data = self._translate(text, dest, src)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate
token = self.token_acquirer.do(text)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do
self._update()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update
code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
AttributeError: 'NoneType' object has no attribute 'group'
解决办法
重新安装指定版本的googletrans==4.0.0-rc1
pip install googletrans==4.0.0-rc1
# 导入google翻译接口工具
from googletrans import Translator
# 实例化翻译对象
translator = Translator(service_urls=['translate.google.cn'])
# translator = Translator()
result = translator.translate('Hello', dest='zh-CN').text
print(result)
result = translator.detect('Hello').lang
print(result)
加油!
感谢!
努力!
以上是关于Python使用googletrans包进行翻译-AttributeError: ‘NoneType‘ object has no attribute ‘group‘&httpcore._ex的主要内容,如果未能解决你的问题,请参考以下文章
翻译:《实用的Python编程》09_00_Overview