我只是試圖導入中文txt文件並打印出內容。 這裏是我的txt文件的內容是我從網絡,這是簡化的中國版本:http://stock.hexun.com/2013-06-01/154742801.html爲什麼我不能在python中使用編碼顯示中文字符?
起初,我嘗試了這一點:
userinput = raw_input('Enter the name of a file')
f=open(userinput,'r')
print f.read()
f.close()
它可以打開的文件和打印,但什麼是節目亂碼。 然後我嘗試了以下一個與編碼:
#coding=UTF-8
userinput = raw_input('Enter the name of a file')
import codecs
f= codecs.open(userinput,"r","UTF-8")
str1=f.read()
print str1
f.close()
但是,它告訴我一個錯誤消息。 UnicodeEncodeError:'cp950編解碼器不能在位置50:非法多字節序列中編碼字符u'\ u76d8'。
爲什麼會發生該錯誤?如何解決它? 我試過其他的像Big5,cp950等unicode ...但它仍然不起作用。
哪些內容?我複製了文章,它工作得很好。 – aIKid
你能發佈你正在使用的確切文本文件嗎? – SheetJS