本篇內容介紹了“怎么用python讀取utf-8編碼格式的文本文件”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
# 讀取utf-8編碼格式的文本文件 # 這里Python解釋器讀取的是utf-8編碼的字節流,然后再按指定的編碼方式解釋這些字節流 # 這樣就比較好理解亂碼的原因 #coding=utf-8 # When Python reads the encoding it tries to interpret the file as utf-8 # 告訴Python解釋器編譯時采用哪種編碼方式 # 如未設置編碼方式,且解釋器可識別文件(如utf-8編碼格式的文件有的(與編輯器有關)帶有BOM,可供解釋器識別)編碼方式則采用文件編碼方式,反之采用終端默認編碼方式 import sys # reload(sys) # 指定終端默認編碼方式 # sys.setdefaultencoding('utf8') # 獲取終端默認編碼方式 # sys.getdefaultencoding() import codecs def ConvertCN(s): if s[:3] == codecs.BOM_UTF8: s = s[3:] # 若系統默認編碼方式為acsii且未修改默認編碼方式 # s.encode('gbk'):s(文件編碼格式)--(.decode('ascii'))-->unicode--(.encode('gbk'))-->s(gbk編碼格式) (這個過程由終端完成,未指定編碼方式時將采用終端默認編碼方式) # 兼容關系:ASCII --> ISO-8859-1 --> UNICODE(UTF-8,UTF-16,UTF-32) --> UCS(UCS2[與UNICODE兼容],UCS4), ASCII --> GB2312 --> GBK --> GB18030 # 因utf-8向下兼容ascii ascii不向上兼容utf-8,對此處s(utf-8編碼格式)進行ascii解碼成unicode時可能發生錯誤 return s.decode('utf-8') def PrintFile(filename): f = file(filename,'r') for f_line in f.readlines(): print ConvertCN(f_line) f.close() if __name__ == "__main__": PrintFile('OperCodingFile.txt') # Python輸出的是字節流 打印由終端處理 # print 在終端顯示如何是由終端決定的 """ 它大致講解下python中的print原理: When Python executes a print statement, it simply passes the output to the operating system (using fwrite() or something like it), and some other program is responsible for actually displaying that output on the screen. For example, on Windows, it might be the Windows console subsystem that displays the result. Or if you're using Windows and running Python on a Unix box somewhere else, your Windows SSH client is actually responsible for displaying the data. If you are running Python in an xterm on Unix, then xterm and your X server handle the display. To print data reliably, you must know the encoding that this display program expects. 簡單地說,python中的print直接把字符串傳遞給操作系統,所以你需要把str解碼成與操作系統一致的格式。 Windows使用CP936(幾乎與gbk相同),所以這里可以使用gbk。 """ print ConvertCN("\n****** 按任意鍵退出!*******") sys.stdin.readline()
“怎么用python讀取utf-8編碼格式的文本文件”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注創新互聯網站,小編將為大家輸出更多高質量的實用文章!
網站名稱:怎么用python讀取utf-8編碼格式的文本文件-創新互聯
文章網址:http://vcdvsql.cn/article20/eipjo.html
成都網站建設公司_創新互聯,為您提供網站收錄、網站改版、企業建站、移動網站建設、響應式網站、營銷型網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯