在逗号上拆分字符串,但是在双引号中忽略逗号?
我有一些看起来像下面的输入:
I have some input that looks like the following:
A,B,C,"D12121",E,F,G,H,"I9,I8",J,K
逗号分隔值可以是以任何顺序。我想用逗号分割字符串;然而,在一些东西在双引号内的情况下,我需要它来忽略逗号和剥离引号(如果可能的话)。所以基本上,输出将是这个字符串列表:
The comma-separated values can be in any order. I'd like to split the string on commas; however, in the case where something is inside double quotation marks, I need it to both ignore commas and strip out the quotation marks (if possible). So basically, the output would be this list of strings:
['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']
我已经看过一些其他的答案,我认为一个正则表达式将是最好的,但我很恐怖的提出他们。
I've had a look at some other answers, and I'm thinking a regular expression would be best, but I'm terrible at coming up with them.
Lasse是对的;它是一个逗号分隔的值文件,因此您应该使用 csv
模块。一个简单的例子:
Lasse is right; it's a comma separated value file, so you should use the csv
module. A brief example:
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']