![](/img/trans.png)
[英]UnicodeDecodeError: 'ascii' codec can't decode byte … Python 2.7 and
[英]Python 2.7 UnicodeDecodeError: 'ascii' codec can't decode byte
我一直在解析一些帶有特殊字符(捷克語字母)的docx文件(UTF-8編碼的XML)。 當我嘗試輸出到stdout時,一切順利,但我無法將數據輸出到文件,
Traceback(最近一次調用最后一次):
文件“./test.py”,第360行,在
ofile.write(U '\\噸\\噸\\噸\\噸\\噸\\ N')
UnicodeEncodeError:'ascii'編解碼器無法編碼位置37中的字符u'\\ xed':序數不在范圍內(128)
雖然我明確地將word
變量轉換為unicode類型( type(word)
返回unicode),但我試圖用.encode('utf-8)
編碼它我仍然堅持這個錯誤。
以下是現在看到的代碼示例:
for word in word_list:
word = unicode(word)
#...
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word+u'"/>\n')
#...
我也嘗試過以下方法:
for word in word_list:
word = word.encode('utf-8')
#...
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word+u'"/>\n')
#...
即使是這兩者的組合:
word = unicode(word)
word = word.encode('utf-8')
我有點絕望所以我甚至試圖在ofile.write()
編碼單詞變量
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word.encode('utf-8')+u'"/>\n')
我很欣賞任何我做錯的提示。
ofile
是一個字節流,你正在寫一個字符串。 因此,它會嘗試通過編碼為字節字符串來處理您的錯誤。 這通常只對ASCII字符安全。 由於word
包含非ASCII字符,因此失敗:
>>> open('/dev/null', 'wb').write(u'ä')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0:
ordinal not in range(128)
使ofile
文本流通過與打開文件io.open
,與像模式'wt'
,和一個顯式的編碼:
>>> import io
>>> io.open('/dev/null', 'wt', encoding='utf-8').write(u'ä')
1L
另外,您也可以使用codecs.open
用幾乎相同的界面,或者用手工編碼的所有字符串encode
。
Phihag的回答是正確的。 我只是想建議使用顯式編碼手動將unicode轉換為字節字符串:
ofile.write((u'\t\t\t\t\t<feat att="writtenForm" val="' +
word + u'"/>\n').encode('utf-8'))
(也許你想知道如何使用基本機制代替高級魔法和像io.open
這樣的黑魔法。)
在寫入word文檔(.docx)時,我遇到了類似的錯誤。 特別是歐元符號(€)。
x = "€".encode()
這給出了錯誤:
UnicodeDecodeError:'ascii'編解碼器無法解碼位置0中的字節0xe2:序號不在范圍內(128)
我是如何解決的是:
x = "€".decode()
我希望這有幫助!
我在stackoverflow中找到的最佳解決方案是在這篇文章中: 如何解決:“UnicodeDecodeError:'ascii'編解碼器不能解碼字節”放入代碼的開頭,默認編碼將是utf8
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.