目前,我想分析其中有4个项目每行由逗号分隔的CSV文件。例如:蟒蛇用逗号分开,忽略一个引号
1, "2,3", 4, 5
我怎样才能把它分成:
[1,"2,3",4,5]
我尝试使用csv.reader
,但结果仍然是错误的方式。谁能帮忙? THX!
目前,我想分析其中有4个项目每行由逗号分隔的CSV文件。例如:蟒蛇用逗号分开,忽略一个引号
1, "2,3", 4, 5
我怎样才能把它分成:
[1,"2,3",4,5]
我尝试使用csv.reader
,但结果仍然是错误的方式。谁能帮忙? THX!
csv.reader
不会做类型转换,但这样的事情或许是:
In [1]: import csv
In [2]: data = ['1, "2,3", 4, 5']
In [3]: next(csv.reader(data, skipinitialspace=True))
Out[3]: ['1', '2,3', '4', '5']
"""
[xxx.csv]
1, "2,3", 4, 5
"""
import re
f = open("xxx.csv")
line = f.readline() # line = '1, "2,3", 4, 5'
startUnit = False # " is for start or end
token = ""
answer=[]
for i in line:
if startUnit==False and re.match("[0-9]", i):
answer.append(int(i))
elif i=='"':
if startUnit==True:
answer.append(token)
startUnit = not startUnit
elif startUnit==True:
token+=i
elif startUnit==False:
token=""
print answer
这是简单的例子。 它可以使其他例外,因为代码仅用于您的示例。 (1,“2,3”,4,5) 我希望它有助于您
你是怎样尝试使用'csv.reader',怎么是结果错了吗? – Ryan 2013-04-20 18:25:47
见http://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python?rq=1 – jarmod 2013-04-20 18:33:41