2013-04-20 88 views
0

目前,我想分析其中有4个项目每行由逗号分隔的CSV文件。例如:蟒蛇用逗号分开,忽略一个引号

1, "2,3", 4, 5

我怎样才能把它分成:

[1,"2,3",4,5]

我尝试使用csv.reader,但结果仍然是错误的方式。谁能帮忙? THX!

+10

你是怎样尝试使用'csv.reader',怎么是结果错了吗? – Ryan 2013-04-20 18:25:47

+0

见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

回答

2

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'] 
+0

如果OP不想要的“自然”型转换,或者'list(ast.literal_eval(line))'或'json.loads('[{}]'.format(line))'应该可以工作。 – DSM 2013-04-20 18:52:06

+0

@DSM - 你说得对。此刻,我回答了更多的预感,OP忘记了引号:) – root 2013-04-20 18:55:32

0
""" 
[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) 我希望它有助于您

相关问题