Python csv模块拆分字符串,而不仅仅是字段

2024-06-28 11:06:38 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个输入(另存为变量'line'):

xsc_i,202,"House of Night",21,"/21_202"

通过csv阅读器:

^{pr2}$

它分割字符串,而不仅仅是字段

['x']
['s']
['c']
['_']
['i']
['', '']
['2']
['0']
['2']
['', '']

等等

即使我显式设置了分隔符,它也会显示这种行为:

csv.reader(line, delimiter=",")

它将字符串视为数组,但我不知道为什么,而且我不能只在逗号上拆分,因为在输入的“”字符串中有许多逗号。在

Python2.7,如果重要的话。在


Tags: ofcsv字符串line数组readerhouse阅读器
3条回答

^{}的第一个参数应该是包含csv行的iterable对象。在您的例子中,输入是一个包含一行的字符串(也是iterable)。您需要将line括在一个列表中:

for row in csv.reader([line]):
    print row

演示:

^{pr2}$

以防万一您想看到re在工作。在

import re
line='xsc_i,202,"House of Night",21,"/21_202"'
print map(lambda x:x.strip('"'),re.split(r',(?=(?:[^"]*"[^"]*")*[^"]*$)',line))

输出:['xsc_i', '202', 'House of Night', '21', '/21_202']

这是因为csv.reader期望

any object which supports the iterator protocol and returns a string each time its next() method is called

您已将字符串传递给了读取器。在

如果你说:

line = ['xsc_i,202,"House of Night",21,"/21_202"',]

您的代码应该按预期工作。 请参见docs

相关问题 更多 >