使用Python读取UTF8 CSV文件 [英] Reading a UTF8 CSV file with Python

查看:359
本文介绍了使用Python读取UTF8 CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Python读取带重音字符的CSV文件(只有法语和/或西班牙语字符)。基于csvreader的Python 2.5文档( http://docs.python.org/library/csv) .html ),我想出了以下代码来读取CSV文件,因为csvreader只支持ASCII。

  def unicode_csv_reader(unicode_csv_data,dialect = csv.excel,** kwargs):
#csv.py不做Unicode;编码为UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect = dialect,** kwargs)
对于csv_reader中的行:
#decode UTF -8返回Unicode,逐个单元格:
yield [unicode(cell,'utf-8')for row in row]

def utf_8_encoder(unicode_csv_data):
在unicode_csv_data中的行:
yield line.encode('utf-8')

filename ='output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for reader1中的field1,field2,field3:
...

下面是我试图阅读的CSV文件的摘要:

  0665000FS10120684, SD1200IS,Appareil photonumériquePowerShot de 10 Mpx de Canon avectrépied(SD1200IS) -  Bleu 
0665000FS10120689,SD1200IS,Appareil photonumériquePowerShot de 10 Mpx de Canon avectrépied(SD1200IS) - Gris
0665000FS10120687,SD1200IS, Appareil photonumériquePowerShot de 10 Mpx de Canon avectrépied(SD1200IS) - Vert
...



<即使我尝试编码/解码为UTF-8,我仍然得到以下异常:

  Traceback最近调用最后):
文件.\Test.py,第53行,在< module>
在reader中的field1,field2,field3:
文件.\Test.py,第40行,在unicode_csv_reader中
对于csv_reader中的行:
文件.\ Unicode编码解码器无法解码位置68中的字节0xc3:序列号(ASCII码)不在范围(128)

如何解决此问题?


< .encode 方法将应用于Unicode字符串以生成字节字符串;但是你调用它的字节串,而不是错误的方式!看看标准库中的编解码器模块和 codecs.open ,特别是更好的一般解决方案,以阅读UTF-8编码文本文件。但是,对于 csv 模块,你需要传入utf-8数据,这就是你已经得到的,所以你的代码可以更简单: / p>

  import csv 

def unicode_csv_reader(utf8_data,dialect = csv.excel,** kwargs):
csv_reader = csv.reader(utf8_data,dialect = dialect,** kwargs)
对于csv_reader中的行:
yield [unicode(cell,'utf-8')for row in row]

filename ='da.csv'
reader = unicode_csv_reader(open(filename))
对于读取器中的field1,field2,field3:
print field1,field2,field3

PS:如果结果是你的输入数据不在utf-8,在ISO-8859-1中,你需要一个转码(如果你热衷于在 csv 模块级别使用utf-8) code> line.decode('whateverweirdcodec')。encode('utf-8') - 但是你可以使用你现有的编码名称 yield ,而不是'utf-8' csv 实际上会很好用ISO-8859- *编码bytestrings。


I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (http://docs.python.org/library/csv.html), I came up with the following code to read the CSV file since the csvreader supports only ASCII.

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
    products = []
    for field1, field2, field3 in reader:
        ...

Below is an extract of the CSV file I am trying to read:

0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...

Even though I try to encode/decode to UTF-8, I am still getting the following exception:

Traceback (most recent call last):
  File ".\Test.py", line 53, in <module>
    for field1, field2, field3 in reader:
  File ".\Test.py", line 40, in unicode_csv_reader
    for row in csv_reader:
  File ".\Test.py", line 46, in utf_8_encoder
    yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)

How do I fix this?

解决方案

The .encode method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs module in the standard library and codecs.open in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:

import csv

def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
  print field1, field2, field3 

PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv module level), of the form line.decode('whateverweirdcodec').encode('utf-8') -- but probably you can just use the name of your existing encoding in the yield line in my code above, instead of 'utf-8', as csv is actually going to be just fine with ISO-8859-* encoded bytestrings.

这篇关于使用Python读取UTF8 CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆