所以我试图将 JSON 文件解析为制表符分隔文件。解析似乎工作正常,所有数据都通过了。尽管最奇怪的事情发生在输出文件上。我告诉它使用制表符分隔符,并且在输出中确实使用制表符,但它似乎仍然保留单引号。出于某种原因,它似乎也在开头添加了字母 B。我手动输入标题,效果很好,但数据本身很奇怪。这是我得到的输出示例。
id created text screen name name latitude longitude place name place type
b'1234567890' b'Thu Mar 14 19:39:07 +0000 2013' "b""I'm at Bank Of America (Wayne, MI) http://t.co/asdf""" b'userid' b'username' 42.28286837 -83.38487864 b'Bank Of America, Wayne' b'poi'
b'1234567891' b'Thu Mar 14 19:39:16 +0000 2013' b'here is a sample tweet \xf0\x9f\x8f\x80 #notingoodhands' b'userid2' b'username2'
这是我用来写出数据的代码。
out = open(filename, 'w')
out.write('id\tcreated\ttext\tscreen name\tname\tlatitude\tlongitude\tplace name\tplace type')
out.write('\n')
rows = zip(ids, times, texts, screen_names, names, lats, lons, place_names, place_types)
from csv import writer
csv = writer(out, dialect='excel', delimiter = '\t')
for row in rows:
values = [(value.encode('utf-8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
out.close()
事情是这样的。如果我在没有 utf-8 位的情况下这样做并直接输出它,那么格式将完全符合我的要求。但是当人们输入特殊字符时,程序会崩溃并且无法处理。
Traceback (most recent call last):
File "tweets.py", line 34, in <module>
csv.writerow(values)
File "C:\Python33\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f3c0' in position 153: character maps to <undefined>
添加 utf-8 位会将其转换为您在此处看到的输出类型,但随后会将所有这些字符添加到输出中。有人对此有任何想法吗?
最佳答案
您正在将字节数据而不是 unicode 写入文件,因为您自己对数据进行编码。
完全删除 encode
调用,让 Python 为您处理;使用 UTF8 编码打开文件,其余部分自行处理:
out = open(filename, 'w', encoding='utf8')
这记录在 csv
module documentation 中:
Since
open()
is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (seelocale.getpreferredencoding()
). To decode a file using a different encoding, use the encoding argument of open:import csv with open('some.csv', newline='', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row)
The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.
关于python - Python CSV 编写器正在将字母添加到每个元素的开头并出现编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15420467/