根据这个答案,我似乎可以用csv.reader(data, delimiter=",", quotechar='"')
解析CSV文件的每一行,所以我做了以下MWE(最小工作示例):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
data = """
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3"""
csvReader = csv.reader(data, delimiter=",", quotechar='"')
for row in csvReader:
print(row)
但是,这段代码不是获取每个行(或者至少是特定单元格中的每一行),而是捕获单元格中的每一个字符。这是输出:
['1']
['', '']
['A towel,']
['', '']
['1']
['.']
['0']
[]
['4']
['2']
['', '']
[' it says, ']
['', '']
['2']
['.']
['0']
[]
['1']
['3']
['3']
['7']
['', '']
['i']
['s']
[' ']
['a']
['b']
['o']
['u']
['t']
[' ']
['t']
['h']
['e']
[' ']
['m']
['o']
['s']
['t']
[' ']
['', '']
['-']
['1']
[]
['0']
['', '']
['m']
['a']
['s']
['s']
['i']
['v']
['e']
['l']
['y']
[' ']
['u']
['s']
['e']
['f']
['u']
['l']
[' ']
['t']
['h']
['i']
['n']
['g']
[' ']
['', '']
['1']
['2']
['3']
[]
['-']
['2']
['', '']
['a']
['n']
[' ']
['i']
['n']
['t']
['e']
['r']
['s']
['t']
['e']
['l']
['l']
['a']
['r']
[' ']
['h']
['i']
['t']
['c']
['h']
['h']
['i']
['k']
['e']
['r']
[' ']
['c']
['a']
['n']
[' ']
['h']
['a']
['v']
['e']
['.']
['', '']
['3']
如您所见,输出解析不是预期的解析。
我想要这样的东西:
[[1],["A towel],["],[1.0]],
[[42],[" it says],[ "],[2.0]],
[[1337],[is about the most ],[-1]],
[[0],[massively useful thing ],[123]],
[[-2],[an interstellar hitchhiker can have.],[3]]
那么,如何正确解析CSV变量呢?
编辑
所以,当它是一个给定的字符变量或打开的文件时,它似乎不工作。错误来自这里。
From csv:
csv。Reader (csvfile, dialect='excel', **fmtparams)
返回一个reader对象,该对象将遍历给定csvfile中的行。csvfile可以是任何支持迭代器协议的对象,每次下一个返回一个字符串。()方法被调用——文件对象和列表对象都是合适的。
from io import StringIO
data = '''
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
'''
with StringIO(data) as f:
csvReader = csv.reader(f)
for row in csvReader:
print(row)
['1', 'A towel,', '1.0']
['42', ' it says, ', '2.0']
['1337', 'is about the most ', '-1']
['0', 'massively useful thing ', '123']
['-2', 'an interstellar hitchhiker can have.', '3']
这将字符串转换为一个类似文件的对象,csv.reader
可以遍历行。你看到的是csv。Reader遍历字符串中的字符。