如何快速解析字符串列表

时间:2022-10-26 20:56:34

If I want to split a list of words separated by a delimiter character, I can use

如果我想拆分由分隔符分隔的单词列表,我可以使用

>>> 'abc,foo,bar'.split(',')
['abc', 'foo', 'bar']

But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?

但是如果我还想处理可以包含分隔符字符的带引号的字符串,如何轻松快速地做同样的事情呢?

In: 'abc,"a string, with a comma","another, one"'
Out: ['abc', 'a string, with a comma', 'another, one']

Related question: How can i parse a comma delimited string into a list (caveat)?

相关问题:如何将逗号分隔的字符串解析为列表(警告)?

2 个解决方案

#1


36  

import csv

input = ['abc,"a string, with a comma","another, one"']
parser = csv.reader(input)

for fields in parser:
  for i,f in enumerate(fields):
    print i,f    # in Python 3 and up, print is a function; use: print(i,f)

Result:

结果:

0 abc
1 a string, with a comma
2 another, one

#2


7  

The CSV module should be able to do that for you

CSV模块应该能够为您做到这一点

#1


36  

import csv

input = ['abc,"a string, with a comma","another, one"']
parser = csv.reader(input)

for fields in parser:
  for i,f in enumerate(fields):
    print i,f    # in Python 3 and up, print is a function; use: print(i,f)

Result:

结果:

0 abc
1 a string, with a comma
2 another, one

#2


7  

The CSV module should be able to do that for you

CSV模块应该能够为您做到这一点