我正在尝试解析(和转义)以Windows-1251字符编码存储的 CSV 文件的行。使用这个出色的答案来处理这种编码,我最终用这一行来测试输出,出于某种原因,这可行:
print(row[0]+','+row[1])
输出:
Тяжелый Уборщик Обязанности,1 литр
虽然这条线不起作用:
print("{0},{1}".format(*row))
输出此错误:
Name,Variant
Traceback (most recent call last):
File "Russian.py", line 26, in <module>
print("{0},{1}".format(*row))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128)
以下是 CSV 的前 2 行:
Name,Variant
Тяжелый Уборщик Обязанности,1 литр
如果有帮助,这里是 Russian.py 的完整来源:
import csv
import cgi
from chardet.universaldetector import UniversalDetector
chardet_detector = UniversalDetector()
def charset_detect(f, chunk_size=4096):
global chardet_detector
chardet_detector.reset()
while 1:
chunk = f.read(chunk_size)
if not chunk: break
chardet_detector.feed(chunk)
if chardet_detector.done: break
chardet_detector.close()
return chardet_detector.result
with open('Russian.csv') as csv_file:
cd_result = charset_detect(csv_file)
encoding = cd_result['encoding']
csv_file.seek(0)
csv_reader = csv.reader(csv_file)
for bytes_row in csv_reader:
row = [x.decode(encoding) for x in bytes_row]
if len(row) >= 6:
#print(row[0]+','+row[1])
print("{0},{1}".format(*row))