CSV不是标准格式,但如果它们出现在文本内部(例如"text"":""a,b,c,d"),则使用两个""来转义引号是很常见的。 Python的CSV阅读器在这里正在做正确的事情,因为它采用了这种惯例。我不太确定您对输出的期望是什么,但这是我尝试使用非常简单的CSV阅读器,它可能适合您的格式。随意调整它。
raw = [
'"1,2,3" , "4,5,6" , "456,789"',
'"text":"a,b,c,d", "gate":"456,789"',
'1,2, 3,'
]
for line in raw:
i, quoted, row = 0, False, []
for j, c in enumerate(line):
if c == ',' and not quoted:
row.append(line[i:j].strip())
i = j + 1
elif c == '"':
quoted = not quoted
row.append(line[i:j+1].strip())
for i in range(len(row)):
if len(row[i]) >= 2 and row[i][0] == '"' and row[i][-1] == '"':
row[i] = row[i][1:-1] # remove quotation marks
print row输出:
['1,2,3', '4,5,6', '456,789']
['text":"a,b,c,d', 'gate":"456,789']
['1', '2', '3', '']