解析一个CSV字符串?

Ahm*_*mad 13 python csv parsing python-2.7

有没有一种方法可以解析单个逗号分隔的字符串而不使用像csv.reader(..)这样的任何想法?我可以使用该split(',')函数,但当有效列值包含逗号本身时,该函数不起作用.csv库有读者解析CSV文件,正确处理上述特殊情况,但我不能使用它们,因为我需要解析一个字符串.但是,如果Python CSV允许解析单个字符串本身,那么这对我来说就是新闻.

lar*_*sks 23

仔细查看该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.
Run Code Online (Sandbox Code Playgroud)

所以如果你有字符串:

>>> s = '"this is", "a test", "of the csv", "parser"'
Run Code Online (Sandbox Code Playgroud)

并且你想要"一个为每次迭代返回一行输入的对象",你可以将你的字符串包装在一个列表中:

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

这就是你用csv模块解析字符串的方式.

  • 我想使用“iter(s)”作为通用迭代器而不是“[s]”(指定一个列表)会更优雅。但你有我的+1 (3认同)
  • `list(csv.reader(['"this is", "a test", "of the csv", "parser"']))[0]` 砰! (2认同)

ale*_*cxe 16

您仍然可以使用解析单个字符串csv.使用StringIO编写字符串缓冲区(也称为内存文件):

import csv
from StringIO import StringIO

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

reader = csv.reader(buff)
for line in reader:
    print(line)
Run Code Online (Sandbox Code Playgroud)

  • 对于Python 3,请使用`from io import StringIO`,参见[here](https://docs.python.org/3/library/io.html#text-io) (5认同)

nac*_*son 7

>>> import csv
>>> s = '"Yes, this line",can be, parsed as csv'
>>> list(csv.reader([s]))[0]
['Yes, this line', 'can be', ' parsed as csv']
>>>
Run Code Online (Sandbox Code Playgroud)

基本上只是@larsks回答了上面的问题,但更简短了一点,表明它适用于在引号内带有逗号的csv值。

如果您支持我,请也支持其他答案。/sf/answers/2507599951/