写在最前面:
由于经常用到Google翻译,想着使用python调用googletrans进行翻译。
很简单的调用,看代码
from py_translator import Translator
s = Translator().translate(text='Hello my friend',dest='zh-cn').text
print(s)
然后控制台一直没反应,等了好久超时。
网上找了一圈,类似这种报错的
Traceback (most recent call last):
File "", line 1, in
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'
我一开始也遇到过,当时我的代码是
from googletrans import Translator
translator = Translator(service_urls=['translate.google.cn'])
source = '我还是不开心!'
text = translator.translate(source,src='zh-cn',dest='en').text
print(text)
这是网上的例子,有大神给出的解决办法是
$ pip uninstall googletrans
$ git clone https://github.com/BoseCorp/py-googletrans.git
$ cd ./py-googletrans
$ python setup.py install
其实不用这么复杂,只要这里改一下即可
translator = Translator()
这样的确是不报错了,可是超时
至于版本一定要用1.8.9么,我没有验证过,有兴趣的同学可以研究下
$ pip3 install py_translator==1.8.9
from py_translator import Translator
还是超时!!!
运行一下
朋友你好
修改源码不用讲了吧,找到py_translator中的gtoken.py,urls.py 和client.py,用文本编辑框改一下即可,举个栗子
def __init__(self, tkk='0', session=None, host='translate.google.com'):
self.session = session or requests.Session()
self.tkk = tkk
self.host = host if 'http' in host else 'https://' + host
把
translate.google.com
改为
translate.google.cn
记得三个都要改,注释的可以不改,都改了最好。
我怎么这么啰嗦。