[英]Python 3 encode error Google Translate API
我正在尝试使用Google Translate API转换以UTF16-BE编码的文本文件的内容,如以下网站上所述: https : //ctrlq.org/code/19909-google-translate-api 。 我希望输出文件使用相同的编码。
以下是我的代码中的一些摘要:
...
import json
import urllib
from urllib.request import Request, urlopen
import urllib.parse
...
def googletranslate(sourceLang, targetLang, sourceText):
url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLang + "&tl=" + targetLang + "&dt=t&q=" +
urllib.parse.quote_plus(sourceText)
urld = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
jsonfile = urlopen(urld).read()
h = json.loads(jsonfile)
return h[0][0][0]
...
input = [line.rstrip('\n') for line in open('input.txt', 'r', encoding="utf_16_be")]
output = open('output.txt', 'w', encoding="utf_16_be")
...
for y in range(offset,offset+size):
text = input[y]
text = googletranslate('auto', '<desired language>', text)
text.encode('utf_16_be')
print("T: " + text)
output.write(text + '\n')
...
但是,当我尝试运行此代码时,它适用于大多数行,但最终我会收到如下错误:
T: <translated text>
Traceback (most recent call last):
File "C:\PATH\TO\translate.py", line 124, in googletranslate
output.write(text + '\n')
File "C:\PATH\TO\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u0259' in position 22: character maps to <undefined>
我该怎么做才能防止此错误? 似乎在命令提示符下可以正常打印。 仅在尝试写入输出文件时给我一个错误。 我应该选择其他编码吗? UTF16-BE是否不足以用于Google翻译的文本?
提前致谢!
Python尝试将文本写入输出文件时将其编码为cp1252(标准Windows编码)。 如果没有将编码参数传递给open
函数,则会发生这种情况-实际代码中是否可能是这种情况,但示例没有?
有两种可能的解决方案。
传递encoding
参数open
,并将模式设置为'w'
,就像在示例代码中所做的那样,然后将str
传递给文件的write
方法。
with open('output.txt', 'w', encoding="utf_16_be") as f:
f.write(text)
在没有编码参数的'wb'
模式下打开文件,然后将编码后的字节写入文件。
with open('output.txt', 'wb') as f:
f.write(text.encode('utf_16_be'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.