1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

py-translator を使ってみる(IndexError: list index out of rangeエラーの回避)

Last updated at Posted at 2018-12-07

https://pypi.org/project/py-translator/ に従って、installして実行してみた。

https://pypi.org/project/py-translator/ より引用:

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”

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?