2016-03-06 66 views
5

有没有办法,我可以解析一个逗号分隔的字符串,而不使用像csv.reader(..)一样的花哨?我可以使用split(',')函数,但在有效列值本身包含逗号时不起作用。 csv库有解析正确处理上述特例的CSV文件的读者,但是我不能使用这些文件,因为我需要解析一个字符串。但是,如果Python CSV允许解析单个字符串本身,那么这对我来说是新闻。解析一个CSV字符串?

回答

11

以在文档中的csv模块, 说,仔细一看:

reader(...) 
    csv_reader = reader(iterable [, dialect='excel'] 
          [optional keyword args]) 
     for row in csv_reader: 
      process(row) 

    The "iterable" argument can be any object that returns a line 
    of input for each iteration, such as a file object or a list. The 
    optional "dialect" parameter is discussed below. The function 
    also accepts optional keyword arguments which override settings 
    provided by the dialect. 

所以,如果你有字符串:

>>> s = '"this is", "a test", "of the csv", "parser"' 

而且你想“一个对象返回一行每个 迭代”的输入,你可以包装你的字符串列表:

>>> r = csv.reader([s]) 
>>> list(r) 
[['this is', 'a test', 'of the csv parser']] 

这就是你如何分析与csv模块的字符串。

+0

我想它会更优雅'iter(s)'作为一般迭代器而不是'[s]'(指定一个列表)。但是你有我的+1 – RafaelC

+0

如果字符串在值的内部引用了换行符,这可能不会起作用; @ alecxe的答案更有意义 – swooby

9

您仍然可以使用csv解析单个字符串。使用StringIO的写一个字符串buffer(也称为内存中的文件):

import csv 
from StringIO import StringIO 

s = "your string" 
buff = StringIO(s) 

reader = csv.reader(buff) 
for line in reader: 
    print(line) 
+0

对于Python 3,使用'from io import StringIO'请参阅[这里](https://docs.python.org/3/library/io.html#text-io) –