天天看點

Python讀取檔案,使用split進行分割時,出現\ufeff

1.問題

使用python3.6對檔案讀取時,按照正常套路處理,檔案内容類似以下:

啊啊啊 || AAA

不不不 || BBB

當使用utf-8讀取文檔并且使用split函數分割時,發現第一行字元分割後,莫名多了一個\ufeff。

因為這個原因,導緻後續使用 == 或者 x in list 操作時,涉及到第一行的資料時,出錯。

Debug第一行見下圖(第二行以後是沒問題的)

Python讀取檔案,使用split進行分割時,出現\ufeff

2.原因

參考1:

The Unicode character U+FEFF is the byte order mark, or BOM, and is used to tell the difference between big- and little-endian UTF-16 encoding

參考2

\ufeff是一個特殊的辨別,表明編碼方式,

位元組序,也就是位元組的順序,指的是多位元組的資料在記憶體中的存放順序,在幾乎所有的機器上,多位元組對象都被存儲為連續的位元組序列,根據資訊在連續記憶體中的存儲順序,位元組序被分為大端序(Big Endian) 與 小端序(Little Endian)兩類。( 然後就牽涉出兩大CPU派系:一派如PowerPC 970等處理器采用 Big Endian方式存儲資料,另一派如x86系列等處理器采用Little Endian方式存儲資料)。其中大端序和小端序解釋如下:

  • Big Endian 是指低位址端 存放 高位位元組。
  • Little Endian 是指低位址端 存放 低位位元組。
對其作用及更多内容見參考

3.解決方法

一種方法:

通過utf-8對字元串進行encode成byte數組,然後再對該byte數組使用utf-8-sig進行decode,即:

templateList = []
    for line in open('templateResult.txt', encoding='utf-8'):
        tmps = line.strip().split('|')
        templateList.append(tmps[0].encode(
            'utf-8').decode('utf-8-sig').strip().replace('。', ''))      

另一種方法,直接使用‘utf-8-sig’打開檔案:

templateList = []
    for line in open('templateResult.txt', encoding='utf-8-sig'):
        tmps = line.strip().split('|')
        templateList.append(tmps[0].strip().replace('。', ''))      

  

4.總結

寫文檔或者讀文檔是python經常用到的操作,如使用open('test.txt',encoding='utf-8')的方式打開文檔,當在處理第一行資料的時候可能由于自己忽略導緻問題。

本文對出錯的原因及解決辦法進行了說明。

參考:

https://stackoverflow.com/questions/17912307/u-ufeff-in-python-string

https://songlee24.github.io/2015/05/02/endianess/

-----------------------------------------

有問題不怕,解決思路很重要!

轉載于:https://www.cnblogs.com/rocly/p/9561585.html