python - 解析单个 CSV 字符串?

标签 python python-2.7 parsing csv

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

最佳答案

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

关于python - 解析单个 CSV 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822822/

相关文章:

parsing - Powershell:引用解析的不一致/奇怪行为?

python - 在python中,如何根据特定值将文件解析为列表?

python - 如何在 Django 中使用过滤后的数据填充表

Python -m 切换到运行包内的模块

python - 用一个空格替换非 ASCII 字符

python - Django 管理员添加自定义过滤器

Python,删除文件夹中早于 X 天的所有文件

json - Python : Interesting json. 转储序列化怪癖

Python 数据帧 : how can I return the number of occurrences in a column?

python - json.load() 函数给出奇怪的 'UnicodeDecodeError: ' ascii'编解码器无法解码'错误