chardet 的英文字縮寫是
“charset(字符集) detection”,
意思是編碼偵測。
chardet 是 Python 的一個套件,
可以自動判斷文字檔案的編碼方式,
通常用在處理 CSV、JSON、XML 等純文字檔案時,
可以先使用 chardet 套件來判斷檔案的編碼,
再使用正確的編碼方式進行讀取,
避免因編碼不同而導致的資料解析錯誤。
import os
import chardet
import pandas as pd
folder = r"C:\Temp"
fname = "test.txt"
fpath = os.path.join(folder,fname)
#'C:\\Temp\\test.txt'
with open(fpath, 'rb') as f:
result = chardet.detect(f.read())
# "charset(字符集) detection"
“””注意要使用rb模式開檔,
不然會出現TypeError
File C:\ProgramData\Anaconda\lib\site-packages\chardet\__init__.py:36 in detect
raise TypeError(‘Expected object of type bytes or bytearray, got: ‘
TypeError: Expected object of type bytes or bytearray, got: <class ‘str’>
“””
print("charset(字符集) detection:\n",result)
df = pd.read_csv(fpath, encoding=result['encoding'])

推薦hahow線上學習python: https://igrape.net/30afN






![Python 如何做excel的樞紐分析? pandas.DataFrame.groupby() ; .agg( {column name: function name} ) ; 如何讀取多層index的xlsx檔案? df = pandas.read_excel (fpath, index_col =[0,1]) ; 如何顯示所有欄? pd.set_option ( “display.max_columns”, None) Python 如何做excel的樞紐分析? pandas.DataFrame.groupby() ; .agg( {column name: function name} ) ; 如何讀取多層index的xlsx檔案? df = pandas.read_excel (fpath, index_col =[0,1]) ; 如何顯示所有欄? pd.set_option ( “display.max_columns”, None)](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230321113121_64.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言