【问题标题】:Create a csv file from multiple dictionaries?从多个字典创建一个 csv 文件?
【发布时间】:2017-05-01 05:37:11
【问题描述】:

我正在计算多个文本文件(140 个文档)中单词的频率,我的工作结束是创建一个 csv 文件,我可以在其中按单个文档和所有文档对每个单词的频率进行排序。

假设我有:

absolut_freq= {u'hello':0.001, u'world':0.002, u'baby':0.005}
doc_1= {u'hello':0.8, u'world':0.9, u'baby':0.7}
doc_2= {u'hello':0.2, u'world':0.3, u'baby':0.6}
...
doc_140={u'hello':0.1, u'world':0.5, u'baby':0.9}

所以,我需要一个 cvs 文件以导出到 excel 中,如下所示:

WORD,  ABS_FREQ, DOC_1_FREQ, DOC_2_FREQ, ..., DOC_140_FREQ
hello, 0.001     0.8         0.2              0.1
world, 0.002     0.9         0.03             0.5
baby,  0.005     0.7         0.6              0.9

我如何用 python 做到这一点?

【问题讨论】:

标签: python csv dictionary


【解决方案1】:

您还可以将其转换为 Pandas Dataframe 并将其保存为 csv 文件或以干净的格式继续分析。

absolut_freq= {u'hello':0.001, u'world':0.002, u'baby':0.005}
doc_1= {u'hello':0.8, u'world':0.9, u'baby':0.7}
doc_2= {u'hello':0.2, u'world':0.3, u'baby':0.6}
doc_140={u'hello':0.1, u'world':0.5, u'baby':0.9}


all = [absolut_freq, doc_1, doc_2, doc_140]

# if you have a bunch of docs, you could use enumerate and then format the colname as you iterate over and create the dataframe
colnames = ['AbsoluteFreq', 'Doc1', 'Doc2', 'Doc140']


import pandas as pd

masterdf = pd.DataFrame()

for i in all:
    df = pd.DataFrame([i]).T
    masterdf = pd.concat([masterdf, df], axis=1)

# assign the column names
masterdf.columns = colnames

# get a glimpse of what the data frame looks like
masterdf.head()

# save to csv 
masterdf.to_csv('docmatrix.csv', index=True)

# and to sort the dataframe by frequency
masterdf.sort(['AbsoluteFreq'])

【讨论】:

    【解决方案2】:

    您可以使其成为一个主要由数据驱动的过程(仅给出所有字典变量的变量名),首先创建一个包含所有数据的table,然后使用csv 模块将转置的(交换行的列)版本写入输出文件。

    import csv
    
    absolut_freq = {u'hello': 0.001, u'world': 0.002, u'baby': 0.005}
    doc_1 = {u'hello': 0.8, u'world': 0.9, u'baby': 0.7}
    doc_2 = {u'hello': 0.2, u'world': 0.3, u'baby': 0.6}
    doc_140 ={u'hello': 0.1, u'world': 0.5, u'baby': 0.9}
    
    dic_names = ('absolut_freq', 'doc_1', 'doc_2', 'doc_140')  # dict variable names
    
    namespace = globals()
    words = namespace[dic_names[0]].keys()  # assume dicts all contain the same words
    table = [['WORD'] + list(words)]  # header row (becomes first column of output)
    
    for dic_name in dic_names:  # add values from each dictionary given its name
        table.append([dic_name.upper()+'_FREQ'] + list(namespace[dic_name].values()))
    
    # Use open('merged_dicts.csv', 'wb') for Python 2.
    with open('merged_dicts.csv', 'w', newline='') as csvfile:
        csv.writer(csvfile).writerows(zip(*table))
    
    print('done')
    

    生成的 CSV 文件:

    WORD,ABSOLUT_FREQ_FREQ,DOC_1_FREQ,DOC_2_FREQ,DOC_140_FREQ
    world,0.002,0.9,0.3,0.5
    baby,0.005,0.7,0.6,0.9
    hello,0.001,0.8,0.2,0.1
    

    【讨论】:

      【解决方案3】:

      不管你想怎么写这个数据,首先你需要一个有序的数据结构,比如一个二维列表:

      docs = []
      docs.append( {u'hello':0.001, u'world':0.002, u'baby':0.005} )
      docs.append( {u'hello':0.8, u'world':0.9, u'baby':0.7} )
      docs.append( {u'hello':0.2, u'world':0.3, u'baby':0.6} )
      docs.append( {u'hello':0.1, u'world':0.5, u'baby':0.9} )
      words = docs[0].keys()
      result = [ [word] + [ doc[word] for doc in docs ] for word in words ]
      

      那么你可以使用内置的csv模块:https://docs.python.org/2/library/csv.html

      【讨论】:

        猜你喜欢
        • 2016-03-08
        • 1970-01-01
        • 2020-02-06
        • 2017-07-25
        • 2016-09-03
        • 1970-01-01
        • 2011-10-08
        • 2012-12-15
        相关资源
        最近更新 更多