有没有一种方法可以在不使用像 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/