解析单个CSV字符串?

26

有没有一种方法可以解析单个逗号分隔的字符串,而不使用任何类似csv.reader(..)这样的高级功能? 我可以使用split(',') 函数,但是当一个有效列值本身包含逗号时,它就不起作用了。CSV库具有用于解析CSV文件的读取器,可正确处理上述特殊情况,但我无法使用它们,因为我需要解析单个字符串。但是,如果Python CSV本身允许解析单个字符串,那对我来说就是好消息。

4个回答

44

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


1
我想使用iter(s)作为通用迭代器而不是指定列表的[s]会更加优雅。但你有我的赞成。 - rafaelc
如果字符串的值中包含引用的换行符,则此方法可能无法正常工作;@alecxe的答案更合理。 - swooby
4
list(csv.reader(['"this is", "a test", "of the csv", "parser"']))[0] 爆炸!(这个代码是用Python语言写的,它的功能是将包含CSV格式字符串的列表解析为二维数组,然后返回第一行数据) - nackjicholson
@rafaelc 更加优雅,但会给您错误的结果。 - G M

21

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

import csv
from StringIO import StringIO

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

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

12
对于 Python 3,请使用 from io import StringIO,详见这里 - Christian Groleau
但是要小心非ASCII字符串!“如果使用Unicode和8位字符串,则无法解释为7位ASCII(使用第8位)的8位字符串将在调用getvalue()时引发UnicodeError。” - Elias Strehle

14
>>> 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://dev59.com/e1sV5IYBdhLWcg3wwhLw#35822856


1

字符串转换为 Pandas 数据框:

import pandas as pd
from io import StringIO

csv_str="Column1,Column2\n1,2\n3,4"

buff = StringIO(csv_str)
df = pd.read_csv(buff)

数据框:

Out[1]: 
   Column1  Column2
         1        2
         3        4

对于其他分隔符,可以像read_csv()一样添加delimiter="\t"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接