Python 解析单个 CSV 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35822822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:00:47  来源:igfitidea点击:

Parse a single CSV string?

pythonpython-2.7parsingcsv

提问by Ahmad

Is there a way that I can parse a single comma delimited string without using anything fancy like a csv.reader(..) ? I can use the split(',')function but that doesn't work when a valid column value contains a comma itself. The csv library has readers for parsing CSV files which correctly handle the aforementioned special case, but I can't use those because I need to parse just a single string. However if the Python CSV allows parsing a single string itself then that's news to me.

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

回答by larsks

Take a closer look at the documentation for the csvmodule, which says:

仔细查看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.

So if you have string:

所以如果你有字符串:

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

And you want "an object that returns a line of input for each iteration", you can just wrap your string in a list:

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

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

And that's how you parse a string with the csvmodule.

这就是您使用csv模块解析字符串的方式。

回答by alecxe

You can still parse a single string with csv. Use StringIO to write a string buffer(also known as memory files):

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

import csv
from StringIO import StringIO

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

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

回答by nackjicholson

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

Basically just @larsks answer above but more brief and demonstrating that it works on csv values that have commas inside quotes.

基本上只是@larsks 上面的答案,但更简短并证明它适用于引号内有逗号的 csv 值。

If you upvote me, upvote the other answer too. https://stackoverflow.com/a/35822856/1196339

如果您给我点赞,也请点赞另一个答案。https://stackoverflow.com/a/35822856/1196339