概念性:将字典结果的2D矩阵写入Python中的CSV文件

时间:2016-12-11 17:25:00

标签: python csv dictionary export-to-csv

我有这样格式化的字典:密钥是文档编号和关键字的元组,值是文档中关键字的频率。 因此,键将是(document1,keyword1),(document1,keyword2),(document1,keyword3),(document2,keyword1),(document2,keyword2),(document2,keyword3),(document3,keyword1),(document3) ,keyword2)和(document3,keyword3),值为数字。当然这是一本小字典。我希望将解决方案应用于大量文档和关键字。

字典是这样创建的:

document_count = {}
try:
    for doc in document_id_list:
        indiv_doc = # records selected from a database
        for w in words:
            document_count.setdefault((doc, w), 0)
            for entry in #unsorted list of text tokenized, set to lower case, and stripped of stop words:
                if entry == w and (doc, entry) in document_count:
                        document_count[(patent, entry)] += 1
    return document_count

except Exception, e:
    print "create claim storages"
    print str(e)
    pass

我想将结果写成类似2D矩阵的CSV。至少,这就是我所看到的描述。

      keyword1 keyword2 keyword3
document1 number   number   number
document2 number   number   number 
document3 number   number   number

在查看python.org上的CSV函数文档和本网站上的其他问题时,我所接近的最接近的是:

document1 keyword1 number
document1 keyword2 number
document1 keyword3 number
document2 keyword1 number
document2 keyword2 number
document2 keyword3 number
document3 keyword1 number
document3 keyword2 number
document3 keyword3 number 

这是我写过的代码的结果:

 with open(os.path.join('C:/Users/Tara/PyCharmProjects/untitled/csv_results/', file_name),
                    'wb') as csvfile:
   w = csv.writer(csvfile)
   for key, value in available_dict.items():
       separate_keys = list(key)
       w.writerow([separate_keys[0], separate_keys[1], value])

我注意到很多解决方案涉及列表理解,但我不知道正确的if语句是什么。当我写字典或写入CSV文件时,我会进行更改吗?

1 个答案:

答案 0 :(得分:0)

许多现有的python库处理编写csv文件的任务,所以我假设你只想使用简单的python语句和结构。

下面的主要策略是编写生成器函数来创建csv文件的行。为此,该函数首先从字典中提取和排序文档和关键字,然后生成包含关键字的标题行,然后创建并生成每个文档的行

我使用最少数量的列表推导,如果您准备再写几行就可以轻松避免

D = {
    ('doc1', 'key1'): 2, ('doc1', 'key2'): 3, ('doc1', 'key3'): 4,
    ('doc2', 'key1'): 4, ('doc2', 'key2'): 6, ('doc2', 'key3'): 8,
    ('doc3', 'key1'): 6, ('doc3', 'key2'): 9, ('doc3', 'key3'): 12,
}

def gen_rows(D):
    sorted_docs = sorted(set(t[0] for t in D))
    sorted_kwds = sorted(set(t[1] for t in D))
    yield [None,] + sorted_kwds
    for d in sorted_docs:
        yield [d,] + [D.get((d, k), 0) for k in sorted_kwds]

for row in gen_rows(D):
    print(row)

这是输出,准备在csv文件中写入的行列表

[None, 'key1', 'key2', 'key3']
['doc1', 2, 3, 4]
['doc2', 4, 6, 8]
['doc3', 6, 9, 12]