首页 > 解决方案 > Google Translate outputs HTML Entities in Python 3

问题描述

When I try to write French characters to a file, some characters look like

j'ai

I didn't have any issues with Spanish characters. What could I be doing wrong?

"""Translates text into the target language.

Make sure your project is whitelisted.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
from google.cloud import translate

# Instantiates a client
translate_client = translate.Client()


# The target language
target = 'fr'

# Create a list of strings to translate. 
test_list = []
new_list = []
for i in range(1) :
    test_list.insert(i, 'I said, you know what, something, I\'m going to drop everything else off that I was doing and go through a period of a dry spell just to properly give it a chance when I started using it. ')

# Send 128 items per translation request and concatenate resulting translations into one list. (The max items per request for Google translate is 128.)
concat_result = []
for j in range(0, len(test_list), 128):
    new_result = translate_client.translate(
        test_list[j:j + 128], target_language=target)
    concat_result += new_result

count = 0
for list in concat_result :
    print(count, concat_result[count]['translatedText'])
    count += 1

Print result:

0 J'ai dit, vous savez quoi, quelque chose, je vais laisser tomber tout ce que je faisais et traverser une période de sécheresse simplement pour lui donner une chance de bien commencer à l'utiliser.

Please ignore that I am translating a list of strings instead of a string. I was testing sending batch requests.

标签: pythonencodinggoogle-translate

解决方案


编辑


好的,正如预期的那样,问题出在字符串而不是字幕生成上。

Google Translate API 指定其默认输出为 HTML。这就是为什么你得到 HTML 实体而不是原始字符的原因。

您需要在 translate 方法的调用中指定您希望格式为文本而不是 HTML。

就像是:

translate_client.translate(
        test_list[j:j + 128], 
        target_language=target,
        format="text")

您可以在以下位置找到有关参数的更多信息: https ://cloud.google.com/translate/docs/reference/translate?hl=ja

以及有关 Python API 本身在此处阅读其源代码的更多详细信息: https ://github.com/googleapis/google-cloud-python/blob/master/translate/google/cloud/translate_v2/client.py#L164

编辑结束


在我回答之前,我会给你一些建议,因为你似乎是新来的:如果你需要代码方面的帮助,你应该提供一个完整的工作示例。当某人不提供所需的所有上下文和信息时,很难帮助他们。

所以,让我们转向答案......

我将在这里开始一个疯狂的猜测:

您正在使用位于以下位置的 srt 库创建字幕文件: https ://github.com/cdown/srt

--

我刚刚使用以下代码对其进行了测试:

subtitle_generator = srt.parse('''\
   1
   00:31:37,894 --> 00:31:39,928
   Je m'appelle Francisco

   ''')

subtitles = list(subtitle_generator)

with open("a_fr.srt" , "w", encoding='utf-8') as f:
    f.write(srt.compose(subtitles))

它显示了撇号就好了。

您应该检查 subs 的内容和在 parse 函数中使用的原始文本。问题很可能是原始文本而不是 python 打印,因为在编写过程中没有任何东西可以自动将字符转换为 HTML 实体。


推荐阅读