【问题标题】:UTF8 missmatch in script脚本中的 UTF8 不匹配
【发布时间】:2018-11-05 07:01:48
【问题描述】:

我的 Python 脚本有问题。我只是尝试用谷歌翻译 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 â ? |

【问题讨论】:

  • 您不需要编码然后再次解码。默认为 UTF-8 无论如何
  • 该行可以完全删除,因为您忽略了返回值。 r.text 值不受影响。无论如何你都应该使用r.json()
  • 我确实可以重现该问题,但它是 Google 方面的问题,而不是您的 Python 代码。您正在享用 Mojibake。
  • @MartijnPieters 所以没有办法解决这个mojibake?我的意思是,如果我访问链接translate.googleapis.com/translate_a/…,月光会闪烁一小片银色,只有一行的一小部分……”在我的浏览器中,我得到一个没有 mojibake 的文本文件
  • 啊,我们可能正在做一些事情,因为您的浏览器不只是发送该 URL(其中包含空格);它还负责将您的文本编码为 URL 引用的数据。我会再试一试。

标签: python python-3.x python-requests mojibake


【解决方案1】:

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 字典中,并从结果列表中提取了输入和输出行值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2011-06-28
    • 2017-03-18
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多