我的Python脚本有问题。我只是尝试使用Google翻译API翻译一些句子。有些句子在使用特殊的UTF-8编码时会遇到问题,例如ä,ö或ü。无法想象为什么有些句子行得通,而有些句子却行不通。

如果我直接在浏览器中尝试API调用,则可以使用,但是在我的Python脚本中,会出现不匹配的情况。

这是我的脚本的一个小版本,直接显示错误:

# -*- encoding: utf-8' -*-
import requests
import json

satz="Beneath the moonlight glints a tiny fragment of silver, a fraction of a line…"
url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=de&dt=t&q='+satz
r = requests.get(url);
r.text.encode().decode('utf8','ignore')
n = json.loads(r.text);
i = 0
while i < len(n[0]):
    newLine = n[0][i][0]
    print(newLine)
    i=i+1


这是我的结果看起来:

Unter dem Mondschein glänzt ein winziges Silberfragment, ein Bruchteil einer Li
nie â ? |

最佳答案

Google为您提供了Mojibake; JSON响应包含的数据最初是使用UTF-8编码的,但随后使用其他编解码器进行了解码,从而导致数据不正确。

我怀疑Google会这样做,因为它会解码URL参数。过去,URL参数可以用任意数量的编解码器进行编码,而UTF-8现在是相对较新的标准。这是Google的错,而不是您或requests的错。

我发现设置User-Agent标头可以使Google表现更好;即使Mozilla/5.0的(不完整)用户代理在这里也足以让Google在解码URL参数时使用UTF-8。

您还应确保您的URL字符串为properly percent encoded,如果您将字典中的参数传递给params,则requests将负责将这些参数正确添加到URL中:

satz = "Beneath the moonlight glints a tiny fragment of silver, a fraction of a line…"
url = 'https://translate.googleapis.com/translate_a/single?client=gtx&dt=t'
params = {
    'q': satz,
    'sl': 'en',
    'tl': 'de',
}
headers = {'user-agent': 'Mozilla/5.0'}
r = requests.get(url, params=params, headers=headers)
results = r.json()[0]
for inputline, outputline, *__ in results:
    print(outputline)


请注意,我也将源语言和目标语言参数提取到params字典中,并从结果列表中提取了输入和输出行值。

关于python - 脚本中的UTF 8不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50536647/

10-12 17:56