main.py
Browse files
main.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import chardet
|
3 |
+
import ftfy
|
4 |
+
|
5 |
+
def read_csv_with_encoding(file_path):
|
6 |
+
# Detect the file encoding
|
7 |
+
with open(file_path, 'rb') as f:
|
8 |
+
result = chardet.detect(f.read())
|
9 |
+
encoding = result['encoding']
|
10 |
+
|
11 |
+
# Try reading the file with the detected encoding
|
12 |
+
try:
|
13 |
+
df = pd.read_csv(file_path, encoding=encoding)
|
14 |
+
return df
|
15 |
+
except UnicodeDecodeError:
|
16 |
+
# If the detected encoding fails, try other encodings
|
17 |
+
for enc in ['utf-8', 'latin-1', 'cp1252']:
|
18 |
+
try:
|
19 |
+
df = pd.read_csv(file_path, encoding=enc, errors='replace')
|
20 |
+
return df
|
21 |
+
except UnicodeDecodeError:
|
22 |
+
pass
|
23 |
+
|
24 |
+
# If all encodings fail, try fixing the text
|
25 |
+
with open(file_path, 'rb') as f:
|
26 |
+
text = f.read().decode('latin-1', errors='replace')
|
27 |
+
fixed_text = ftfy.fix_text(text)
|
28 |
+
|
29 |
+
try:
|
30 |
+
df = pd.read_csv(io.StringIO(fixed_text), encoding='utf-8')
|
31 |
+
return df
|
32 |
+
except UnicodeDecodeError:
|
33 |
+
print(f"Failed to read {file_path} after trying multiple encodings and text fixes.")
|
34 |
+
return None
|
35 |
+
|
36 |
+
# Example usage
|
37 |
+
file_path = 'path/to/your/csv/file.csv'
|
38 |
+
df = read_csv_with_encoding(file_path)
|
39 |
+
if df is not None:
|
40 |
+
print(df.head())
|
41 |
+
else:
|
42 |
+
print("Failed to read the CSV file.")
|