天天看點

【字元串轉清單生成器】利用Python讀取檔案時出現\ufeff的原因及解決辦法解決方法:

txt_file_path ="關鍵詞清單.txt"

def txt_contents_to_list(txt_file_path):
   # 查找檔案

   # 打開檔案
   f = open(txt_file_path, "r",encoding='utf-8')
   # 讀取内容
   contents=f.read().strip(" ")
   print(contents)
   # 拆分為列
   contents_list = contents.split(",")
   contents_list_0 = contents_list[0][6:]
   print(contents_list_0)

   f.close()
   print("\n"+str(len(contents_list))+":個元素,轉換完成,\n清單為:"+str(contents_list))

txt_contents_to_list(txt_file_path)
           

輸出:

222:個元素,轉換完成,

清單為:['\ufeff毛巾', '小風扇', '迷你小風扇', '置物架',

解決方法:

隻需改一下編碼就行,把 UTF-8 編碼 改成 UTF-8-sig編碼即可

xt_file_path ="關鍵詞清單.txt"

def txt_contents_to_list(txt_file_path):
   # 查找檔案

   # 打開檔案
   f = open(txt_file_path, "r",encoding='UTF-8-sig')
   # 讀取内容
   contents=f.read().strip(" ")
   print(contents)
   # 拆分為列
   contents_list = contents.split(",")
   contents_list_0 = contents_list[0][6:]
   print(contents_list_0)

   f.close()
   print("\n"+str(len(contents_list))+":個元素,轉換完成,\n清單為:"+str(contents_list))

txt_contents_to_list(txt_file_path)
           

繼續閱讀