Python 2-通过csv迭代,确定特定的行作为划片



在这个问题的帮助下,我从多个字典中生成了csv(也是可读和可编辑的)。输出是简单的

//Dictionary
key,value
key2,value2
//Dictionary2
key4, value4
key5, value5

我想用双反斜杠作为分隔符来创建新字典,但每个调用csv.reader(open("input.csv"))都是通过行计算的,所以我不使用:

import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
    dict[key] = val

谢谢你帮我。。

编辑:这是我做的。。井"代码"。。如果你能查看并查看,我会很高兴:

#! /usr/bin/python
import csv
# list of dictionaries 
l = []
# evalute throught csv
for row in csv.reader(open("test.csv")):
    if row[0].startswith("//"):
        # stripped "//" line is name for dictionary
        n = row[0][2:]
        # append stripped "//" line as name for dictionary
        #debug
        print n
        l.append(n)
        #debug print l[:]
    elif len(row) == 2:
        # debug
        print "len(row) %s" % len(row)
        # debug
        print "row[:] %s" % row[:]
        for key, val in row:
            # print key,val
            l[-1] = dic
            dic = {}
            dic[key] = val
# debug
for d in l:
    print l
    for key, value in d:
        print key, value

不幸的是,我收到了这个错误:

DictName
len(row) 2
row[:] ['key', ' value']
Traceback (most recent call last):
  File "reader.py", line 31, in <module>
    for key, val in row:
ValueError: too many values to unpack

考虑不使用CSV

首先,你对数据问题的总体策略可能不是最优的。你的数据看起来越不表格化,将其保存在CSV文件中就越没有意义(尽管你的需求并不太离谱)。

例如,使用json:可以很容易地解决这个问题

import json
# First the data
data = dict(dict1=dict(key1="value1", key2="value2"),
            dict2=dict(key3="value3", key4="value4"))
# Convert and write
js = json.dumps(data)
f = file("data.json", 'w')
f.write(js)
f.close()
# Now read back
f = file("data.json", 'r')
data = json.load(f)
print data

按照书面形式回答问题

然而,如果你真的对这个策略很感兴趣,你可以按照jonrsharpe的建议做一些事情。您不能只使用csv模块来为您完成所有的工作,而是实际上必须遍历并过滤掉(并通过)"//"行。

import csv
import re
def header_matcher(line):
    "Returns something truthy if the line looks like a dict separator"
    return re.match("//", line)

# Open the file and ...
f = open("data.csv")
# create some containers we can populate as we iterate
data = []
d = {}
for line in f:
    if not header_matcher(line):
        # We have a non-header row, so we make a new entry in our draft dictionary
        key, val = line.strip().split(',')
        d[key] = val
    else:
        # We've hit a new header, so we should throw our draft dictionary in our data list
        if d:
            # ... but only if we actually have had data since the last header
            data.append(d)
            d = {}
# The very last chunk will need to be captured as well
if d:
    data.append(d)
# And we're done...
print data

这有点混乱,如果有任何机会需要转义逗号,它会变得更加混乱。如果需要的话,你可能会找到一种聪明的方法,将文件分块到生成器中,用CSV阅读器读取,但这并不是特别干净/容易(我开始了这样的方法,但看起来很痛苦…)。这一切都证明了你的方法可能是错误的数据存储方式。

如果您设置为CSV

如果你真的想要CSV,但又不拘泥于你指定的确切数据格式,另一种方法是:在CSV文件中添加一列,对应于数据应该进入的字典。想象一下,一个文件(data2.csv)如下所示:

dict1,key1,value1
dict1,key2,value2
dict2,key3,value3
dict2,key4,value4

现在我们可以做一些更清洁的事情,比如:

import csv
data = dict()
for chunk, key, val in csv.reader(file('test2.csv')):
    try:
        # If we already have a dict for the given chunk id, this should add the key/value pair
        data[chunk][key] = val
    except KeyError:
        # Otherwise, we catch the exception and add a fresh dictionary with the key/value pair
        data[chunk] = {key: val}
print data

好多了。。。

做一些更接近你想法的事情的唯一好的理由是,如果有很多数据,空间是一个问题。但在大多数情况下,情况并非如此。

还有熊猫

哦,是的。。。另一个可能的解决方案是熊猫。我还没有经常使用它,所以我没有那么多帮助,但它提供了group_by函数,如果你最终像3列CSV方法那样构建数据,它可以让你按第一列分组。

我决定改用json

阅读这篇文章对程序来说更容易,而且不需要过滤文本。为了在外部file.json中生成数据库内部的数据,将服务于python程序。

#! /usr/bin/python
import json
category1 = {"server name1":"ip address1","server name2":"ip address2"}
category2 = {"server name1":"ip address1","server name1":"ip address1"}
servers = { "category Alias1":category1,"category Alias2":category2}
js = json.dumps(servers)
f = file("servers.json", "w")
f.write(js)
f.close()
# Now read back
f = file("servers.json", "r")
data = json.load(f)
print data

因此,输出是包含类别键的字典,而作为值的是另一个字典。正是我想要的。

最新更新