在Python 2.7和Ubuntu 14.04我试图写一个CSV文件:UnicodeEncodeError:使用writerow“ASCII”编解码器不能编码字符错误和地图
csv_w.writerow(map(lambda x: flatdata.get(x, ""), columns))
这给了我臭名昭著
UnicodeEncodeError: 'ascii' codec can't encode character u'\u265b' in position 19: ordinal not in range(128)
错误。
通常建议在这里是用unicode(x).encode("utf-8")
我已经试过这一点,也只是.encode("utf-8")
在获取两个参数:
csv_w.writerow(map(lambda x: flatdata.get(unicode(x).encode("utf-8"), unicode("").encode("utf-8")), columns))
,但我仍然得到同样的错误。
任何帮助非常感谢您摆脱错误。 (我想unicode("").encode("utf-8")
是笨拙的,但我仍然是一个新手)。
编辑: 我的全程序:
抛出错误UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 14: ordinal not in range(128)
#!/usr/bin/env python
import json
import csv
import fileinput
import sys
import glob
import os
def flattenjson(b, delim):
val = {}
for i in b.keys():
if isinstance(b[i], dict):
get = flattenjson(b[i], delim)
for j in get.keys():
val[ i + delim + j ] = get[j]
else:
val[i] = b[i]
return val
def createcolumnheadings(cols):
#create column headings
print ('a', cols)
columns = cols.keys()
columns = list(set(columns))
print('b', columns)
return columns
doOnce=True
out_file= open('Excel.csv', 'wb')
csv_w = csv.writer(out_file, delimiter="\t" )
print sys.argv, os.getcwd()
os.chdir(sys.argv[1])
for line in fileinput.input(glob.glob("*.txt")):
print('filename:', fileinput.filename(),'line #:',fileinput.filelineno(),'line:', line)
data = json.loads(line)
flatdata = flattenjson(data, "__")
if doOnce:
columns=createcolumnheadings(flatdata)
print('c', columns)
csv_w.writerow(columns)
doOnce=False
csv_w.writerow(map(lambda x: flatdata.get(unicode(x).encode("utf-8"), unicode("").encode("utf-8")), columns))
绝密单鸣叫:可用here。
解决方案按照Alistair的建议我安装了unicodescv。 的步骤是:从 here
下载的zip安装:sudo的PIP安装/path/to/zipfile/python-unicodecsv-master.zip
import unicodecsv as csv
csv_w = csv.writer(f, encoding='utf-8')
csv_w.writerow(flatdata.get(x, u'') for x in columns)
你能告诉一个完整的例子,有样本数据,这样我可以重现我的机器上的问题,并帮助? – Will
谢谢!我已经添加了该程序。样本数据是种族主义的推文!这些是1.种族主义者和2.有识别信息。我可以给他们发邮件吗 – schoon
我在dropcanvas上放了一条编辑推文,问题结尾的链接。再次感谢!! – schoon