Python googletrans 编码奇怪的字符

Python googletrans encoding weird chars

我有一个 ui,它把德语和其他语言翻译成英文句子。

# -*- coding: utf-8 -*-
from googletrans import Translator

def tr(s)
  translator =  Translator()
  return translator.translate(wordDE,src='de',dest='en').text

有时我会从翻译那里听到奇怪的字符。 例如:

DE:Pascal 和 PHP sind Programmierspra​​chen für Softwareentwickler und Ingenieure。

googletrans EN(utf8): Pascal 和 PHP 是面向软件开发人员和工程师的编程语言。

这是字符串在 utf8 格式下的样子。当我用 windows 文本编辑器打开它时,它看起来像这样:

googletrans EN: Pascal 和 PHP 是面向软件开发人员和工程师的编程语言。

如您所见,在“for software”之前有 2 个奇怪的字符,即 translate() 函数 returns。这些字符也在 "googletrans EN(utf8)" 字符串中。您看不到它们,但是当您使用箭头键跳过字符串时,光标不会移动“for software” 2 次点击。所以角色在那里但看不见。 (也许你不能在这里做,因为字符串已经从网站上格式化了)

有时也会出现翻译后看不到的其他字符。

我需要删除这些字符。我不能只使用 ascii,因为我还需要在 txt 文件中保护德语字符,如“ö,ä,ü,ß”。这可能只是一个我不明白的编码问题,还是那里出了什么问题?

翻译后的文本包含两个嵌入的零宽度 space (\u200b') 个字符。

>>> res = t.translate(wordDE, src='de', dest='en').text
>>> res
'Pascal and PHP are programming languages \u200b\u200bfor software developers and engineers.'

文本编辑器将文件解码为 cp1252(或类似的 MS 8 位编码),因此 mojibake:

>>> res.encode('utf-8').decode('cp1252')
'Pascal and PHP are programming languages ​​for software developers and engineers.'

这是一个known bug is the Google Translate API. Pending a fix, you can use str.replace,用于创建不包含这些字符的新字符串

>>> new_res = res.replace('\u200b', '')
>>> new_res
'Pascal and PHP are programming languages for software developers and engineers.'