Python使用googletrans包进行翻译
- 问题分析
- 解决办法
问题分析
安装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)
参考:https://stackoverflow.com/questions/52455774/googletrans-stopped-working-with-error-nonetype-object-has-no-attribute-group
加油!
感谢!
努力!