解析一个CSV字符串?

2024-05-13 08:08:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件csv方法函数字符串情况读取器reader
3条回答

您仍然可以使用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)

仔细查看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模块解析字符串的方法。

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

基本上只需@larsks回答上面的问题,但更简短的是,它演示了它在csv值上的工作,这些值在引号中有逗号。

如果你投票给我,也要投票给另一个答案。https://stackoverflow.com/a/35822856/1196339

相关问题 更多 >