我有一些输入如下所示:
A,B,C,"D12121",E,F,G,H,"I9,I8",J,K
逗号分隔值可以按任何顺序排列。我想把字符串分成逗号;但是,如果某些东西在双引号内,我需要它来忽略逗号并去掉引号(如果可能的话)。所以基本上,输出将是这个字符串列表:
['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']
我已经看过其他一些答案了,我认为正则表达式会是最好的,但是我很难想出来。
答案 0 :(得分:58)
Lasse是对的;它是逗号分隔值文件,因此您应该使用csv
module。一个简短的例子:
from csv import reader
# test
infile = ['A,B,C,"D12121",E,F,G,H,"I9,I8",J,K']
# real is probably like
# infile = open('filename', 'r')
# or use 'with open(...) as infile:' and indent the rest
for line in reader(infile):
print line
# for the test input, prints
# ['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']