python - 在python中将unicode UTF-16数据写入文件时出现问题

标签 python unicode

我正在使用 Python 2.6.1 在 Windows 上工作。

我有一个包含单个字符串 Hello 的 Unicode UTF-16 文本文件,如果我在二进制编辑器中查看它,我会看到:

FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00
BOM   H     e     l     l     o     CR    LF

我想做的是读入这个文件,通过 Google Translate API 运行它,然后将它和结果写入一个新的 Unicode UTF-16 文本文件。

我写了下面的 Python 脚本(实际上我写了比这更复杂的东西,有更多的错误检查,但它被简化为一个最小的测试用例):

#!/usr/bin/python    
import urllib
import urllib2
import sys
import codecs

def translate(key, line, lang):
    ret = ""
    print "translating " + line.strip() + " into " + lang
    url = "https://www.googleapis.com/language/translate/v2?key=" + key + "&source=en&target=" + lang + "&q=" + urllib.quote(line.strip())
    f = urllib2.urlopen(url)
    for l in f.readlines():
        if l.find("translatedText") > 0 and l.find('""') == -1:
            a,b = l.split(":")
            ret = unicode(b.strip('"'), encoding='utf-16', errors='ignore')
            break
    return ret

rd_file_name = sys.argv[1]
rd_file = codecs.open(rd_file_name, encoding='utf-16', mode="r")
rd_file_new = codecs.open(rd_file_name+".new", encoding='utf-16', mode="w")
key_file = open("api.key","r")

key = key_file.readline().strip()

for line in rd_file.readlines():
    new_line = translate(key, line, "ja")
    rd_file_new.write(unicode(line) + "\n")
    rd_file_new.write(new_line)
    rd_file_new.write("\n")

这给了我一个几乎是 Unicode 的文件,里面有一些额外的字节:

FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00 0A 00
20 22 E3 81 93 E3 82 93 E3 81 AB E3 81 A1 E3 81 AF 22 0A 00 

我可以看到 20 是一个空格,22 是一个引号,我假设“E3”是 urllib2 用来指示下一个字符是 UTF-16 编码的转义字符??

如果我运行相同的脚本,但使用“cs”(捷克语)而不是“ja”(日语)作为目标语言,则响应全部为 ASCII,我得到的 Unicode 文件首先是 UTF- 16 个字符,然后是单字节 ASCII 字符的“Ahoj”。

我确定我遗漏了一些明显的东西,但我看不到什么。我在查询结果上尝试了 urllib.unquote() 但这没有帮助。我还尝试在 f.readlines() 中返回字符串时打印它,这一切看起来都很合理,但很难判断,因为我的终端窗口不正确支持 Unicode。

还有其他尝试的建议吗?我查看了建议的骗局,但似乎没有一个完全符合我的情况。

最佳答案

我相信 Google 的输出是 UTF-8,而不是 UTF-16。试试这个修复:

ret = unicode(b.strip('"'), encoding='utf-8', errors='ignore') 

关于python - 在python中将unicode UTF-16数据写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411757/

相关文章:

c - C中字节的Unicode代码点流?

python - Python 3.4、Unicode、不同的语言和 Windows 有什么关系?

python - ascii 编解码器无法解码字节 0xe9

Python 打印不使用 __repr__、__unicode__ 或 __str__ 作为 unicode 子类?

python - 运行时错误 : Expected object of scalar type Long but got scalar type Float for argument #2 'mat2' how to fix it?

python - 如何抑制python的启动信息?

javascript - 自定义 Intl.Collat​​ors?

python - 如何使用 SCRAPY 向 API 发出 POST 请求

python - 我应该对我的 python 函数/方法进行多少输入验证?

python - numpy.float 和 numpy.float64 之间的区别