解析单个 CSV 字符串?

新手上路,请多包涵

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

原文由 Ahmad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 583
2 个回答

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

原文由 larsks 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 import csv
from StringIO import StringIO

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

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

原文由 alecxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏