【问题标题】:textblob.exceptions.NotTranslated: Translation API returned the input string unchangedtextblob.exceptions.NotTranslated:翻译 API 未更改地返回输入字符串
【发布时间】:2018-12-23 01:27:45
【问题描述】:

我正在尝试通过 textblob 将非英语文本翻译成英语。我阅读了文档并尝试处理如下可能的异常:

txt=" "
for word in text.split():
    try:
        w=TextBlob(word)
        w=w.translate(to='en')

    except TranslatorError(TextBlobError):
        word=" "  #replace word with space
        txt=txt+word
    except NotTranslated(TextBlobError):
         txt=txt+word+" "
    else:
         txt=txt+w+" "
print(txt)  

我收到以下错误:

except TranslatorError(TextBlobError): 
NameError: name 'TranslatorError' is not defined  

raise NotTranslated('Translation API returned the input string unchanged.')
textblob.exceptions.NotTranslated: Translation API returned the input string unchanged.

我参考了以下链接: https://textblob.readthedocs.io/en/dev/api_reference.html#textblob.exceptions.TextBlobError

我无法解决这些错误。请帮忙!

【问题讨论】:

    标签: textblob


    【解决方案1】:

    这对我有用:

    en_blob = TextBlob(u'简单胜于复杂。') print(en_blob.translate(from_lang='en', to='es'))

    明确声明“from_lang”。

    【讨论】:

    • P.S.使用 TextBlob 从英语翻译成英语时出现错误。我创建了一个声明,说明如果语言翻译成!=“en”,然后翻译。现在,我的代码完美运行...
    • 谢谢。但是如果 textblob 无法翻译怎么办?我们需要异常处理
    • 什么意思? Tbh 我决定切换到 pytranslator pypi.org/project/py-translator 我相信他们都使用谷歌翻译 api,所以翻译与 textblob 相同。
    • from py_translator import Translator Translator().translate(text="Hello world, my translation works", dest=new_lang).text
    • 有些文本 Textblob 无法翻译。在这种情况下,Textblob 会引发异常。我有非英语单词与英语文本混合。我想要,如果 Textblob 无法翻译,那么它只是通过替换为“”(空字符串)来跳过并继续下一个非英文文本
    【解决方案2】:

    这只是因为两种语言中的某些单词是相同的。如果我们查看 TextBlob 的文档,它是如何引发异常的:

    它首先翻译单词,所以你调用translate方法,它看起来像:

    def translate(self, source, from_lang='auto', to_lang='en', host=None, type_=None):
        """Translate the source text from one language to another."""
        if PY2:
            source = source.encode('utf-8')
        data = {"q": source}
        url = u'{url}&sl={from_lang}&tl={to_lang}&hl={to_lang}&tk={tk}'.format(
            url=self.url,
            from_lang=from_lang,
            to_lang=to_lang,
            tk=_calculate_tk(source),
        )
        response = self._request(url, host=host, type_=type_, data=data)
        result = json.loads(response)
        if isinstance(result, list):
            try:
                result = result[0]  # ignore detected language
            except IndexError:
                pass
        self._validate_translation(source, result)
        return result
    

    当您看到最后第二行时,它会尝试验证翻译。如果翻译的和源的相同,则抛出异常

    def _validate_translation(self, source, result):
        """Validate API returned expected schema, and that the translated text
        is different than the original string.
        """
        if not result:
            raise NotTranslated('Translation API returned and empty response.')
        if PY2:
            result = result.encode('utf-8')
        if result.strip() == source.strip():
            raise NotTranslated('Translation API returned the input string unchanged.')
    

    例如,如果您尝试将“Plauen”这个词从英语翻译成德语,这是因为 Plauen 这个词在英语和德语中是相同的。

    您可以简单地使用 Python 中的 try 和 except 块来逃避此类异常。

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      错误处理的方式不对,我用了下面的代码,它成功了,希望对你有帮助。

      import textblob.exceptions
      
      txt=" "
      for word in text.split():
          try:
              w=TextBlob(word)
              w=w.translate(to='en')
      
          except textblob.exceptions.TranslatorError:
              word=" "  #replace word with space
              txt=txt+word
          except textblob.exceptions.NotTranslated:
              txt=txt+word+" "
          else:
              txt=txt+w+" "
      print(txt)  
      
           
      

      【讨论】:

        猜你喜欢
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 2011-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        相关资源
        最近更新 更多