Dut*_*tta 0 python csv non-ascii-characters
我有一个 csv 文件,4000 条记录中只有 4 条包含一些非 ASCII 字符。例如
['com.manager', '2016012300', '16.1.23', 'en', 'kinzie', '2015-04-11T17:36:23Z', '1428773783781', '2016-03-11T09:53:45Z', 'df', '5', "\xa5\x06`'", '\xc0\x03"', '\xa2{\xac ===]\xa9}\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7\xf7>', '', '', '', 'https://play.google.com/apps/publish?account=sd#ReviewDetailsPlace:p=com.manager&reviewid=gp:AOqpTOEcQQGmjFcd-bFfU372DTrxh']
Run Code Online (Sandbox Code Playgroud)
我正在使用以下 python 代码来读取 csv
with open('/Users/duttaam/Downloads/test1.csv', 'rU') as csvfile:
reader_obj = csv.reader(x.replace('\0', '') for x in csvfile)
rownum=0
for row in reader_obj:
rownum += 1
if len(row) != 16:
print rownum
print row
Run Code Online (Sandbox Code Playgroud)
对于四行,阅读器显示不一致的列号。但是当我计算这些行中的分隔符(,)时,它显示得很好。我能看到的唯一问题是非 ascii 字符,如上行所示的示例行。我猜这些是一些表情符号转换成一些字符。
我想出了一个从字符串中删除不可打印字符的函数,如何将其应用于整个 csv?(感谢以下帖子:Stripping non printable characters from a string in python)
def removeSpecialcahr(s):
printable = set(string.printable)
return filter(lambda x: x in printable, s)
Run Code Online (Sandbox Code Playgroud)
有没有办法处理 csv 并删除所有不可打印和/或非 ascii 字符?
要从文件中删除非 ASCII 字符,请将您的open调用替换为codecs.open(). 您还可以定义自己的错误处理程序...:
import codecs
codecs.open('file.csv', 'r', encoding='ascii', errors='ignore')
Run Code Online (Sandbox Code Playgroud)