有没有一种方法可以解析单个逗号分隔的字符串,而不使用像 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
模块解析字符串的方式。
@rafaelc 建议
iter(s)
可能更优雅,但不幸的是 iter(s)
将返回 s
中的 characters的迭代器。也就是说,给定:
s = "'this is', 'a test', 'of the csv parser'"
r = csv.reader(iter(s))
for row in r:
print(row)
我们会得到如下输出:
["'"]
['t']
['h']
['i']
['s']
[' ']
['i']
['s']
["'"]
.
.
.
我认为没有任何方法可以在单个字符串上创建行迭代器,这比简单地将其包装在列表中更好。
正如 @alexce 在他们的回答中指出的那样,我们可以使用
StringIO
对象实现类似的效果,但这需要更多的开销。比较包裹在列表中的 s
的大小:
>>> sys.getsizeof([s])
64
>>> sys.getsizeof(io.StringIO(s))
184
(还有导入
io
模块的成本,需要内存和时间)。
您仍然可以使用
csv
解析单个字符串。使用StringIO写入字符串buffer(也称为内存文件):
import csv
from StringIO import StringIO
s = "your string"
buff = StringIO(s)
reader = csv.reader(buff)
for line in reader:
print(line)
>>> 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 值。
如果您支持我,请也支持其他答案。 https://stackoverflow.com/a/35822856/1196339
字符串到 Pandas DataFrame:
import pandas as pd
from io import StringIO
csv_str="Column1,Column2\n1,2\n3,4"
buff = StringIO(csv_str)
df = pd.read_csv(buff)
数据框:
Out[1]:
Column1 Column2
1 2
3 4
对于其他分隔符,请将
delimiter="\t"
添加到 read_csv()
。