将非ASCII字符编码为UTF-16
我想知道怎么把一些非ASCII字符(也就是那些ASCII码大于127的字符,比如ö、ä、ü等)用UTF-16编码,这样“é”就变成“\u00e9”,“Ř”就变成“\u0158”。我尝试的方法是把字符转换成十六进制,然后把前两个字符替换成“\u00”(因为这是UTF-16的格式)。但是这样做并没有成功,结果得到了一些乱码。请帮我找一个正确的算法。
这是我写的代码,但转换结果不对:
f = open ("input.txt","r")
data = f.read()
x=list(data)
i=0
for element in x:
if ord(element)>127:
y=hex(ord(x[i]))
y=y[2:]
y='\u00'+y
x[i]=y
i=i+1
data=''.join(x)
t= open("output.txt","w")
t.write(data)
f.close()
t.close()
4 个回答
0
使用字符串自带的 encode
方法:
# A string with a single, non-ascii character.
s = '\u00e9'
# UTF-16 encoding beginning with a byte-order-mark to identify its endianness.
s.encode('utf-16') # b'\xff\xfe\xe9\x00'
# UTF-16 big-endian, no byte-order-mark.
s.encode('utf-16-be') # b'\x00\xe9'
# UTF-16 little-endian, no byte-order-mark.
s.encode('utf-16-le') # b'\xe9\x00'
0
以二进制模式打开文件
with open(filename,"rb") as f:
print f.read()
如果这样还不行,可以试试内置的codecs
import codecs
with codecs.open(filename,"rb",encoding="utf8") as f:
print f.read()
0
@TokenMacGuy 在一个你已经删除的旧问题上发表了这个回答,问题链接是 这里。因为有足够声望的用户仍然可以看到被删除的问题,所以我把它复制粘贴到这里给你:
所以你想把unicode转换成一种ascii表示方式,其中非ascii的字符会被“转义”?如果是这样,可以试试:
>>> sample = u'some stuff: éŘ'
>>> ''.join(c if 0 < ord(c) <= 127 else '\\u{:04x}'.format(ord(c)) for c in sample)
u'some stuff: \\u00e9\\u0158'
>>> print ''.join(c if 0 < ord(c) <= 127 else '\\u{:04x}'.format(ord(c)) for c in sample)
some stuff: \u00e9\u0158
顺便说一下,这个算法不是utf-16;请不要这样称呼它,它是ASCII!UTF-16长这样:
>>> sample.encode('utf-16')
'\xff\xfes\x00o\x00m\x00e\x00 \x00s\x00t\x00u\x00f\x00f\x00:\x00 \x00\xe9\x00X\x01'
注意:你没有说明,所以这个例子是用python2.7写的,不是python3;如果你需要python3,请在你的问题中添加说明
我不确定这是否对你有帮助。或者也许@TokenMacGuy自己会编辑这个回答,让它更有帮助。