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.
我正在尝试读取带有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 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:
下面是我要读的CSV文件的摘录:
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:
即使我尝试对UTF-8编码/解码,我仍然得到以下的例外:
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?
我怎么解决这个问题?
6 个解决方案
#1
99
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:
将.encode方法应用到Unicode字符串,以生成字节字符串;但是你用一个字节字符串来代替…错误的方式“圆!在标准库和编解码器中查看codecs模块。打开特别是为更好的通用解决方案阅读UTF-8编码的文本文件。但是,对于csv模块,您需要传递utf-8数据,这是您已经得到的,所以您的代码可以简单得多:
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.
PS:如果事实证明你的输入数据不是在utf - 8中,但如在iso - 8859 - 1,那么你需要一个“代码转换”(如果你热衷于使用utf - 8在csv模块级),表单的line.decode(whateverweirdcodec).encode(“utf - 8”),但可能你可以使用现有的编码的名称在上面的屈服在我的代码中,而不是“utf - 8”,csv实际上是很好使用iso - 8859 - * bytestrings编码。
#2
43
Python 2.X
There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.
有一个unicode-csv库,它可以解决您的问题,并增加了没有naving来编写任何新的csv相关代码的好处。
Here is a example from their readme:
下面是他们自述的一个例子:
>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ
Python 3.X
In python 3 this is supported out of the box by the build-in csv
module. See this example:
在python 3中,内置的csv模块支持这一功能。看这个例子:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
#3
3
Also checkout the answer in this post: https://*.com/a/9347871/1338557
也可以在本文中查看答案:https://*.com/a/9347871/1338557。
It suggests use of library called ucsv.py. Short and simple replacement for CSV written to address the encoding problem(utf-8) for Python 2.7. Also provides support for csv.DictReader
它建议使用名为ucsv.py的库。用于解决Python 2.7的编码问题(utf-8)的CSV编写的简短而简单的替换。还提供对csv.DictReader的支持。
Edit: Adding sample code that I used:
编辑:添加我使用的示例代码:
import ucsv as csv
#Read CSV file containing the right tags to produce
fileObj = open('awol_title_strings.csv', 'rb')
dictReader = csv.DictReader(fileObj, fieldnames = ['titles', 'tags'], delimiter = ',', quotechar = '"')
#Build a dictionary from the CSV file-> {<string>:<tags to produce>}
titleStringsDict = dict()
for row in dictReader:
titleStringsDict.update({unicode(row['titles']):unicode(row['tags'])})
#4
1
The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes). Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable data). I assume that your file should be read correctly without any conversions.
对于python 2.6来说,帮助页面的链接也是一样的,据我所知,csv模块自2.5(除bug修复之外)没有变化。这是一个没有任何编码/解码(文件da)的代码。csv包含与变量数据相同的数据)。我假定您的文件应该正确读取,而不需要任何转换。
test.py:
test.py:
## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#
import csv
data = \
"""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"""
# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
print (f1, f2, f3)
# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
print (f1, f2, f3)
da.csv:
da.csv:
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
#5
1
Using codecs.open
as Alex Martelli suggested proved to be useful to me.
使用编解码器。正如Alex Martelli所建议的那样,被证明对我有用。
import codecs
delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
row = line.split(delimiter)
# do something with your row ...
#6
0
Looking at the Latin-1
unicode table, I see the character code 00E9
"LATIN SMALL LETTER E WITH ACUTE". This is the accented character in your sample data. A simple test in Python
shows that UTF-8
encoding for this character is different from the unicode (almost UTF-16
) encoding.
查看LATIN -1 unicode表,我看到字符代码00E9“拉丁小写字母E和急性”。这是您的示例数据中的重音字符。Python中的一个简单测试表明,该字符的UTF-8编码与unicode(几乎是UTF-16)编码不同。
>>> u'\u00e9'
u'\xe9'
>>> u'\u00e9'.encode('utf-8')
'\xc3\xa9'
>>>
I suggest you try to encode("UTF-8")
the unicode data before calling the special unicode_csv_reader()
. Simply reading the data from a file might hide the encoding, so check the actual character values.
我建议您在调用特殊的unicode_csv_reader()之前尝试对unicode数据进行编码(“UTF-8”)。简单地从文件中读取数据可能隐藏编码,因此检查实际的字符值。
#1
99
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:
将.encode方法应用到Unicode字符串,以生成字节字符串;但是你用一个字节字符串来代替…错误的方式“圆!在标准库和编解码器中查看codecs模块。打开特别是为更好的通用解决方案阅读UTF-8编码的文本文件。但是,对于csv模块,您需要传递utf-8数据,这是您已经得到的,所以您的代码可以简单得多:
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.
PS:如果事实证明你的输入数据不是在utf - 8中,但如在iso - 8859 - 1,那么你需要一个“代码转换”(如果你热衷于使用utf - 8在csv模块级),表单的line.decode(whateverweirdcodec).encode(“utf - 8”),但可能你可以使用现有的编码的名称在上面的屈服在我的代码中,而不是“utf - 8”,csv实际上是很好使用iso - 8859 - * bytestrings编码。
#2
43
Python 2.X
There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.
有一个unicode-csv库,它可以解决您的问题,并增加了没有naving来编写任何新的csv相关代码的好处。
Here is a example from their readme:
下面是他们自述的一个例子:
>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ
Python 3.X
In python 3 this is supported out of the box by the build-in csv
module. See this example:
在python 3中,内置的csv模块支持这一功能。看这个例子:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
#3
3
Also checkout the answer in this post: https://*.com/a/9347871/1338557
也可以在本文中查看答案:https://*.com/a/9347871/1338557。
It suggests use of library called ucsv.py. Short and simple replacement for CSV written to address the encoding problem(utf-8) for Python 2.7. Also provides support for csv.DictReader
它建议使用名为ucsv.py的库。用于解决Python 2.7的编码问题(utf-8)的CSV编写的简短而简单的替换。还提供对csv.DictReader的支持。
Edit: Adding sample code that I used:
编辑:添加我使用的示例代码:
import ucsv as csv
#Read CSV file containing the right tags to produce
fileObj = open('awol_title_strings.csv', 'rb')
dictReader = csv.DictReader(fileObj, fieldnames = ['titles', 'tags'], delimiter = ',', quotechar = '"')
#Build a dictionary from the CSV file-> {<string>:<tags to produce>}
titleStringsDict = dict()
for row in dictReader:
titleStringsDict.update({unicode(row['titles']):unicode(row['tags'])})
#4
1
The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes). Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable data). I assume that your file should be read correctly without any conversions.
对于python 2.6来说,帮助页面的链接也是一样的,据我所知,csv模块自2.5(除bug修复之外)没有变化。这是一个没有任何编码/解码(文件da)的代码。csv包含与变量数据相同的数据)。我假定您的文件应该正确读取,而不需要任何转换。
test.py:
test.py:
## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#
import csv
data = \
"""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"""
# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
print (f1, f2, f3)
# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
print (f1, f2, f3)
da.csv:
da.csv:
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
#5
1
Using codecs.open
as Alex Martelli suggested proved to be useful to me.
使用编解码器。正如Alex Martelli所建议的那样,被证明对我有用。
import codecs
delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
row = line.split(delimiter)
# do something with your row ...
#6
0
Looking at the Latin-1
unicode table, I see the character code 00E9
"LATIN SMALL LETTER E WITH ACUTE". This is the accented character in your sample data. A simple test in Python
shows that UTF-8
encoding for this character is different from the unicode (almost UTF-16
) encoding.
查看LATIN -1 unicode表,我看到字符代码00E9“拉丁小写字母E和急性”。这是您的示例数据中的重音字符。Python中的一个简单测试表明,该字符的UTF-8编码与unicode(几乎是UTF-16)编码不同。
>>> u'\u00e9'
u'\xe9'
>>> u'\u00e9'.encode('utf-8')
'\xc3\xa9'
>>>
I suggest you try to encode("UTF-8")
the unicode data before calling the special unicode_csv_reader()
. Simply reading the data from a file might hide the encoding, so check the actual character values.
我建议您在调用特殊的unicode_csv_reader()之前尝试对unicode数据进行编码(“UTF-8”)。简单地从文件中读取数据可能隐藏编码,因此检查实际的字符值。