我正在使用Python解析csv文件。
CSV文件如下所示:
value1,value2,value3(a,b,c)
Python代码:
with open(file_path, 'rb') as this_file:
reader = csv.reader(this_file, delimiter=',')
for row in reader:
print row
显然,CSV阅读器将此解释为:
"value1","value2","value3(","a","b","c)"
阻止Python将value2()分解为四个值的最佳方法是什么?
感谢。
答案 0 :(得分:1)
没有简单的方法可以在值中突破逗号。关于它有几个问题,许多人指出这个帖子: https://stackoverflow.com/a/769713/2620328
答案 1 :(得分:1)
这是一个处理给定示例的代码:
a='value1, value2, value3(a, b, c)'
split=a.split(', ')
result=[]
for ent in split:
if ent.find('(', 0, len(ent))!=-1:
temp=''
for ent2 in split[split.index(ent):]:
if ent2.find('(', 0, len(ent))!=-1:
temp=temp+ent2
else:
temp=temp+','+ent2
split.remove(ent2)
#May need a check whether ) has not been reached yet, in which case don't add the items.
result.append(temp)
else:
result.append(ent)
如果在用括号括起来之后存在一些“正常”条目(如评论中所示),则需要进行一些小的检查,例如
a='value1, value2, value3(a, b, c)', 'value4'
希望这会有所帮助。抱歉,我想不出任何使用内置csv解析器的方法,因为你的文件实际上并不是一个“合适的”csv ......