2013-01-05 73 views
0

在德語單詞(有時含有元音字符)在Excel2007的電子表格(I使用xlrd xlwt和openpyxl)工作時,得到以下值:如何在Python 2.7中打印德語變音符號?

var = str(ws.cell(row=i+k,column=0).value).encode('latin-1') 

我帶有印記得到(VAR):

'[a word') 

直到即將來臨含有元音字符一句話,當我得到:

Traceback (most recent call last): 
    File "C:\Users\cristina\Documents\horia\Linguistics3\px t3.py", line 68, in <module> 
    var = str(ws4.cell(row=i+k,column=0).value).encode('latin-1') 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 3:ordinal not in range(128) 

,然後程序停止。

如果我定義VAR爲:

var = u'str(ws4.cell(row=i+k,column=0).value)'.encode('latin-1') 

我得到,當母雞試圖打印(VAR),我得到:

var=str(ws.cell(row=i+k,column=0).value) 

程序正常運行,直到最後

我可以在Python Shell中獲得var的值,但不能在程序中使用「print(var)」。

有人可以給我一個解決方案嗎?

+0

嘗試使用.encode(」 utf-8')或.encode('latin1','ignore')... – Infinity

+0

'print ws4.cell(row = i + k,column = 0).value.encode('latin-1')'也許? –

+0

@Hedde,不,這不是重複 – oefe

回答

2

首先,讀取此:http://www.joelonsoftware.com/articles/Unicode.html(嚴重)

然後,明白Python2具有兩個不同的數據類型: unicode的,對於「不可知」移交所有可能的字符,但是其可以NT中可以使用 輸入/輸出,如「打印」或寫入文件,不用編碼進入 其他數據類型:字符串。

字符串是編碼依賴的。

我幾乎可以肯定的是,因爲你的錯誤消息,ws4.cell(row=i+k,column=0).value調用正在返回一個unicode值。 (我無法在這裏的非Windows環境中測試它) - 爲了確保您獲得unicode值,您可能希望在那裏使用 print (type(ws4.cell(row=i+k,column=0).value)來運行一次,而不是猜測。

因此,當你做str(ws4.(...).value)時,你告訴Python只需將unicode轉換爲str而不用任何編碼 - 這是引發錯誤的調用,而不是隨後的「解碼」調用。

如果這到底是怎麼回事,只需更換str呼籲unicode

var = u'str(ws4.cell(row=i+k,column=0).value)'.encode('latin-1') 

這應該解決您的問題。我希望你讀過我上面鏈接的文章 - 它有幫助。

此外,請使用您正在使用的相應編碼標記您的Python源代碼 - 否則您的源代碼中的任何非ASCII字符將會出現錯誤 。

例如,寫上你的代碼的第一行:

# coding: latin1 

(儘管對於任何嚴肅的項目,你應該使用UTF-8來代替。)

相關問題