2013-03-07 96 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'