在逗号上拆分字符串但忽略双引号内的逗号?

Xåp*_* - 41 python regex csv split double-quotes

我有一些输入,如下所示:

A,B,C,"D12121",E,F,G,H,"I9,I8",J,K
Run Code Online (Sandbox Code Playgroud)

逗号分隔值可以按任何顺序排列.我想把字符串分成逗号; 但是,如果某些东西在双引号内,我需要它来忽略逗号并去掉引号(如果可能的话).所以基本上,输出将是这个字符串列表:

['A', 'B', 'C', 'D12121', 'E', 'F', 'G', 'H', 'I9,I8', 'J', 'K']
Run Code Online (Sandbox Code Playgroud)

我已经看过其他一些答案,而且我认为正则表达式会是最好的,但是我很难想出来.

agf*_*agf 59

拉斯是对的; 它是逗号分隔值文件,因此您应该使用该csv模块.一个简短的例子:

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']
Run Code Online (Sandbox Code Playgroud)

  • @heltonbiker我对Python也有这种感觉 - 感觉就像你有时根本没做任何事情,它仍然有效:) (6认同)