2013-03-07 85 views
0

如何编码UTF-16中字符串(ö,ä,ü等)的非ascii(ascii> 127)字符,以便“é”变为“ \ u00e9“和”Ř“变成”\ u0158“。我所做的是将char转换为十六进制,并用\ u00替换前两个字符(对于UTF-16)。但这不起作用......给我垃圾价值。请帮助我一个正确的算法。将非ASCII字符编码为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() 
+2

你之前问过这个问题,但删除了它。我将再次解释:了解Unicode和编码*首先*。 UTF-16有两种口味:小字节和大字节。 * UTF-16中的所有*字符编码为两个字节,只处理非ASCII字符*无用*。 – 2013-03-07 16:33:24

+0

'open(“input.txt”,“rb”)'你需要打开它来阅读二进制文件...然后试着打印它 – 2013-03-07 16:33:39

+1

你见过http://pymotw.com/2/codecs/吗? – Borealid 2013-03-07 16:35:42

回答

0

@TokenMacGuy已发布此回答给the old question which you've deleted。由于用户具有足够的声誉可以仍然看到被删除的问题,我的复制粘贴它为你在这里:


所以你想从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;如果你需要,请把它添加到你的问题


我不知道这会帮助你。或者,也许@TokenMacGuy自己将编辑这个答案,使其更有帮助。

0

以二进制方式

with open(filename,"rb") as f: 
    print f.read() 

打开该文件,如果不工作尝试编解码器内置

import codecs 

with codecs.open(filename,"rb",encoding="utf8") as f: 
    print f.read() 
0

使用内置encode method of strings

# 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

从问题中不清楚您是要将字符作为文字字符串'\u00xx',还是希望Unicode字符串中包含正确的字符。

要将字符直接转换为Unicode,您必须确定它们最初创建的代码页,并将其与decode一起使用。我在这里猜测代码页852,因为这是我能找到的第一个包含Ř的代码。

>>> data = '\x82\xfc' 
>>> x = data.decode('cp852') 
>>> x 
u'\xe9\u0158' 
>>> print x 
éŘ 

如果你想快速地将其转换为只包含与一个转义序列代替非ASCII字符的ASCII字符串,使用unicode-escape编码。

>>> y = x.encode('unicode-escape') 
>>> y 
'\\xe9\\u0158' 
>>> print y 
\xe9\u0158 

Windows 1250 code page还包含Ř,但在不同的值。同样的技术也适用于那里。

>>> data2 = '\xe9\xd8' 
>>> data2.decode('windows-1250') 
u'\xe9\u0158'