【googletrans包】Python谷歌翻译

慎俊雄
2023-12-01

python谷歌翻译

参考文章:
python 调用谷歌翻译接口


报错:

$python P4_omim_unique_pheid_tran.py 
<googletrans.client.Translator object at 0x7f2b26201b10>
Traceback (most recent call last):
  File "/share/home/wyz/Lab/Database/OMIM/script/P4_omim_unique_pheid_tran.py", line 58, in <module>
    print(translator.translate('中国人'))
  File "/share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans/client.py", line 172, in translate
    data = self._translate(text, dest, src)
  File "/share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans/client.py", line 75, in _translate
    token = self.token_acquirer.do(text)
  File "/share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans/gtoken.py", line 200, in do
    self._update()
  File "/share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans/gtoken.py", line 65, in _update
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

参考文章:
Python3 googletrans谷歌翻译出错:‘NoneType‘ object has no attribute ‘group‘
https://blog.csdn.net/xfyuanjun520/article/details/115465873

卸载旧包

$pip uninstall googletrans
Found existing installation: googletrans 2.4.0
Uninstalling googletrans-2.4.0:
  Would remove:
    /share/home/wyz/miniconda3/envs/py3lab/bin/translate
    /share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans-2.4.0.dist-info/*
    /share/home/wyz/miniconda3/envs/py3lab/lib/python3.10/site-packages/googletrans/*
Proceed (Y/n)? Y
  Successfully uninstalled googletrans-2.4.0

安装新包

pip install googletrans==4.0.0-rc1

结果,安装失败

$pip install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple googletrans
# /googletrans-3.0.0.dist-info/*
# 结果失败

$pip install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple google_trans_new
Successfully installed google_trans_new-1.1.9
# 结果失败

pip uninstall googletrans
pip uninstall google_trans_new

$pip install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple googletrans==4.0.0-rc1
# Successfully installed googletrans-4.0.0rc1
# 结果成功

运行代码示例

from googletrans import Translator

translator = Translator(service_urls=['translate.google.cn'])# 如果可以上外网,还可添加 'translate.google.com' 等
print(translator)
trans=translator.translate('Hello World', src='en', dest='zh-cn')
# trans=translator.translate('Hello World',src='en', dest='zh-cn')
print(trans)
# # 原文
print(trans.origin)
print(type(trans.origin))
# 译文
print(trans.text)
print(type(trans.text))

执行结果

$python P4_omim_unique_pheid_tran.py 
<googletrans.client.Translator object at 0x7f813a07df90>
Translated(src=en, dest=zh-cn, text=你好世界, pronunciation=Nǐ hǎo shìjiè, extra_data="{'confiden...")
Hello World
<class 'str'>
你好世界
<class 'str'>
Translated(src=zh-CN, dest=en, text=Chinese, pronunciation=None, extra_data="{'confiden...")
 类似资料: