Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解析单个CSV字符串?_Python_Python 2.7_Parsing_Csv - Fatal编程技术网

Python 解析单个CSV字符串?

Python 解析单个CSV字符串?,python,python-2.7,parsing,csv,Python,Python 2.7,Parsing,Csv,有没有一种方法可以在不使用像csv.reader(..)这样的花哨的东西的情况下解析单个逗号分隔的字符串?我可以使用split(',')函数,但当有效列值本身包含逗号时,该函数不起作用。csv库有用于解析csv文件的读卡器,可以正确处理上述特殊情况,但我不能使用这些读卡器,因为我只需要解析单个字符串。但是,如果Python CSV允许解析单个字符串本身,那么这对我来说就是新闻。您仍然可以使用CSV解析单个字符串。使用StringIO写入字符串(也称为内存文件): 仔细查看csv模块的文档,其中

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

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


仔细查看
csv
模块的文档,其中 说:

因此,如果您有字符串:

>>> s = '"this is", "a test", "of the csv", "parser"'
您需要“一个对象,它为每个对象返回一行输入 迭代”,您只需将字符串包装在列表中:

>>> r = csv.reader([s])
>>> list(r)
[['this is', 'a test', 'of the csv parser']]
这就是使用
csv
模块解析字符串的方法

>>> 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值


如果你投我一票,你也要投另一个答案

我想使用
iter
作为通用迭代器比使用
[s]
(指定列表)更优雅。但是您有我的+1如果字符串在值中引用了换行符,那么这可能不起作用@alecxe的答案更有意义
list(csv.reader([''this's'、'test'、'ofthecsv'、'parser'])[0]
Boom!对于Python3,请使用来自io导入字符串io的
请参见,但要小心使用非ASCII字符串如果使用[Unicode和8位字符串],则无法解释为7位ASCII(使用第8位)的8位字符串将在调用getvalue()时引发Unicode错误
>>> r = csv.reader([s])
>>> list(r)
[['this is', 'a test', 'of the csv parser']]
>>> import csv
>>> s = '"Yes, this line",can be, parsed as csv'
>>> list(csv.reader([s]))[0]
['Yes, this line', 'can be', ' parsed as csv']
>>>