Python textblob 翻译 API 错误

4

我一直在Windows上使用Python 2.7.10中的textblob已经有一段时间了,但出乎意料地它停止工作了。在两个独立的虚拟机以及OS X上进行测试都会产生相同的错误。

docs中测试一个简单的片段:

    from textblob import TextBlob
    en_blob = TextBlob(u'Simple is better than complex.')
    print(en_blob.translate(to='es'))

产生一个错误:

File "test.py", line 3, in <module> print(en_blob.translate(to='es'))

File "C:\Python27\lib\site-packages\textblob\blob.py", line 509, in translate
from_lang=from_lang, to_lang=to))

File "C:\Python27\lib\site-packages\textblob\translate.py", line 45, in translate
raise NotTranslated('Translation API returned the input string unchanged.')

textblob.exceptions.NotTranslated: Translation API returned the input string 
unchanged.

我该如何调试这个错误?

4个回答

4
正如文档中所提到的,Textblob使用Google翻译API进行翻译。
显然,这个(未记录的)API已经改变了它的输出格式。我能够使用以下代码片段成功请求:
import requests
url = 'http://translate.google.com/translate_a/t'
params = {
    "text": "Simple is better than complex", 
    "sl": "en", 
    "tl": "es", 
    "client": "p"
}
print(requests.get(url, params=params).content)

>> '"Simple es mejor que complejo"'

在textblob的源代码中,代码指示了一种json编码方法,但显然谷歌在这里决定简单确实比复杂更好。
这个问题已经在https://github.com/sloria/TextBlob/issues/117中提到。

1
我遇到了相同的问题,但是是在语言检测方面而不是翻译。您能否帮助我理解如何使用上述格式进行相同的操作? - Harsh Patni

3

正如@Gijs所提到的,Google翻译API已经发生了变化。这导致TextBlob的翻译和语言检测功能停止工作。

我已经提交了一个PR来解决这个问题。请点击此处查看。


0

引入from_lang参数并不能解决这个问题,根据我的经验。 我已经通过另一个前端调用谷歌翻译API来解决它,而不是通过textblob。 https://github.com/ssut/py-googletrans


0

您只需要设置from_lang参数,告诉翻译的原文语言:

en_blob = TextBlob(u'Simple is better than complex.')
print(en_blob.translate(from_lang='en', to='es'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接