Python正确解析CSV [英] Python Parse CSV Correctly

查看:136
本文介绍了Python正确解析CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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,Ford,E350,

1997,Ford,E350,"Super, luxurious truck"

应拆分为


('1997','Ford','E350','超级豪华卡车')

('1997', 'Ford', 'E350', 'Super, luxurious truck')

b
$ b

and NOT


('1997','Ford','E350','Super','luxury truck'')

('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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆