https://pypi.org/project/py-translator/ に従って、installして実行してみた。
Google Translate - Python Library. The end goal is a simple application for translating text in the terminal. Text can be generated interactively or programmatically in the shell environment.
環境
$ python --version
Python 3.6.7
インストール
$ pip install py_translator==1.8.9
実行
$ python
Python 3.6.7 (default, Nov 15 2018, 16:29:08)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from py_translator import Translator
>>> s = Translator().translate(text='Hello my friend', dest='es').text <== スペイン語に翻訳
>>> print(s)
Hola mi amigo
>>> s = Translator().translate(text='Hello my friend', dest='ja').text <== ja指定してみる
>>> print(s)
こんにちは、友よ
エラーが出る場合
実際のところ、install直後は、次のようなエラーが出ていた
$ python
Python 3.6.7 (default, Nov 15 2018, 16:29:08)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from py_translator import Translator
>>> s = Translator().translate(text='Hello my friend', dest='es').text
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python/lib/python3.6/site-packages/py_translator/client.py", line 172, in translate
data = self._translate(text, dest, src)
File "/usr/local/python/lib/python3.6/site-packages/py_translator/client.py", line 75, in _translate
token = self.token_acquirer.do(text)
File "/usr/local/python/lib/python3.6/site-packages/py_translator/gtoken.py", line 184, in do
self._update()
File "/usr/local/python/lib/python3.6/site-packages/py_translator/gtoken.py", line 56, in _update
self.tkk = self.RE_TKK.findall(r.text)[0]
IndexError: list index out of range
Google updated how token is displayed in response. #8
に従って、
/usr/local/python/lib/python3.6/site-packages/py_translator/gtoken.py
を以下のように修正。
gtoken.py
RE_TKK = re.compile(r'TKK=\'([^\']*)\';', re.DOTALL) <--- この行を消して
RE_TKK = re.compile(r'tkk:\'(.+?)\'', re.DOTALL) <--- この行を追加
参考:py_translator stopped working with “IndexError: list index out of range”