Python 正确解析 CSV [英] Python Parse CSV Correctly
问题描述
我对 Python 非常陌生.我想解析一个 csv 文件,以便它能够识别引用的值 - 例如
I am very new to Python. I want to parse a csv file such that it will recognize quoted values - for example
1997,福特,E350,超级豪华卡车"
1997,Ford,E350,"Super, luxurious truck"
应该拆分为
('1997'、'福特'、'E350'、'超级豪华卡车')
('1997', 'Ford', 'E350', 'Super, luxurious truck')
而不是
('1997', 'Ford', 'E350', '"Super', '豪华卡车'')
('1997', 'Ford', 'E350', '"Super', ' luxurious truck"')
以上是我使用类似 str.split(,)
时得到的结果.
the above is what I get if I use something like str.split(,)
.
我该怎么做?最好将这些值存储在数组或其他数据结构中吗?因为在我从 csv 获取这些值后,我希望能够轻松选择,假设任意两列并将其存储为另一个数组或其他一些数据结构.
How do I do this? Also would it be best to store these values in an array or some other data structure? because after I get these values from the csv I want to be able to easily choose, lets say any two of the columns and store it as another array or some other data structure.
推荐答案
以下方法完美
d = {}
d['column1name'] = []
d['column2name'] = []
d['column3name'] = []
dictReader = csv.DictReader(open('filename.csv', 'rb'), fieldnames = ['column1name', 'column2name', 'column3name'], delimiter = ',', quotechar = '"')
for row in dictReader:
for key in row:
d[key].append(row[key])
列以列名作为键存储在字典中.
The columns are stored in dictionary with the column names as the key.
这篇关于Python 正确解析 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!