MY555's picture
main.py
9bd34f5 verified
import pandas as pd
import chardet
import ftfy
def read_csv_with_encoding(file_path):
# Detect the file encoding
with open(file_path, 'rb') as f:
result = chardet.detect(f.read())
encoding = result['encoding']
# Try reading the file with the detected encoding
try:
df = pd.read_csv(file_path, encoding=encoding)
return df
except UnicodeDecodeError:
# If the detected encoding fails, try other encodings
for enc in ['utf-8', 'latin-1', 'cp1252']:
try:
df = pd.read_csv(file_path, encoding=enc, errors='replace')
return df
except UnicodeDecodeError:
pass
# If all encodings fail, try fixing the text
with open(file_path, 'rb') as f:
text = f.read().decode('latin-1', errors='replace')
fixed_text = ftfy.fix_text(text)
try:
df = pd.read_csv(io.StringIO(fixed_text), encoding='utf-8')
return df
except UnicodeDecodeError:
print(f"Failed to read {file_path} after trying multiple encodings and text fixes.")
return None
# Example usage
file_path = 'path/to/your/csv/file.csv'
df = read_csv_with_encoding(file_path)
if df is not None:
print(df.head())
else:
print("Failed to read the CSV file.")