【问题标题】:Dictionary of lists from two specific columns of a csv file来自 csv 文件的两个特定列的列表字典
【发布时间】:2019-03-26 08:01:59
【问题描述】:

我正在处理的 CSV 文件如下所示:

{http://www.omg.org/XMI}id,begin,end,Emotion
17266,772,781,anticipation
17402,772,781,disgust
17304,1345,1370,disgust
17424,1534,1543,surprise
17424,1534,1543,surprise
17424,1534,1543,surprise
17424,1534,1543,surprise
17472,1578,1602,anger
17525,1611,1617,fear

我正在尝试创建一个列表字典,其中 'Emotion' 条目作为键,'begin'(第二列)作为它们所在行中出现的键的值。

所需的输出如下所示:

{'anger': [1578,
           2853,
           3951,...],
 'anticipation': [772, 4154, 4400...],
...}

到目前为止,我已经成功地输出了所需的输出,但是每个值都是每个键列表中自己的列表。

我当前的代码:

import pickle
from pprint import pprint
import tkinter
from tkinter import filedialog
import csv
from itertools import groupby


root_tk = tkinter.Tk()
root_tk.wm_withdraw()

def extract_gold_emotions():


    """Returns mapping of GOLD emotions to their indices"""



    filename = filedialog.askopenfilename()


    l = list(csv.reader(open(filename)))


    f = lambda x: x[-1]


    gold_emo_offsets = {k:list(sorted(map(int, x[1:2])) for x in v)\
                           for k,v in groupby(sorted(l[1:], key=f), f)}


    pickle.dump(gold_emo_offsets, open("empos.p", "wb"))


    return gold_emo_offsets


my_emotions = extract_gold_emotions()

当前输出:

{'anger': [[1578], [2853], [3951], [4084], [4693], [6420], [8050]],
 'anticipation': [[772], [4154], [4400], [7392]],....]]}

关于在代码中更改什么以输出我想要的列表字典的任何提示?

提前致谢!

编辑:

字典值应输出为整数。

【问题讨论】:

    标签: python list csv dictionary


    【解决方案1】:

    只使用基本的python,没有导入(*):

    写入文件:

    with open("data.csv","w") as w:
        w.write("""{http://www.omg.org/XMI}id,begin,end,Emotion
    17266,772,781,anticipation
    17402,772,781,disgust
    17304,1345,1370,disgust
    17424,1534,1543,surprise
    17424,1534,1543,surprise
    17424,1534,1543,surprise
    17424,1534,1543,surprise
    17472,1578,1602,anger
    17525,1611,1617,fear
    """)
    

    读取和处理文件:

    d = {}
    with open("data.csv","r") as r:
        next(r) # skip header
        for line in r:
            if line.strip(): # ignore empty lines (f.e. the last one)
                l = line.strip().split(",")
                begin = l[1] # the begin column
                emo = l[-1]  # the emotion column
                k = d.setdefault(emo,[]) # get/create key + empty list if needed
                k.append(begin)            # append to key as string
                # k.append(int(begin))     # append to key but convert to int first
    
    print(d)            
    

    输出(附加为字符串):

    {'anger': ['1578'], 
     'surprise': ['1534', '1534', '1534', '1534'], 
     'fear': ['1611'], 
     'anticipation': ['772'], 
     'disgust': ['772', '1345']}
    

    (*):如果 csv 包含转义文本或“内联/转义”分隔符等内容,则不应自己解析它。你的数据是 plain 的,你可以自己解析它。

    【讨论】:

      【解决方案2】:

      您可以使用collections.defaultdict 来获取结果字典:

      from io import StringIO
      import csv
      from collections import defaultdict
      
      text = '''id,begin,end,Emotion
      17266,772,781,anticipation
      17402,772,781,disgust
      17304,1345,1370,disgust
      17424,1534,1543,surprise
      17424,1534,1543,surprise
      17424,1534,1543,surprise
      17424,1534,1543,surprise
      17472,1578,1602,anger
      17525,1611,1617,fear'''
      
      data = defaultdict(list)
      
      with StringIO(text) as file:
          for row in csv.DictReader(file):
              data[row['Emotion']].append(row['begin'])
      
      print(data)
      

      【讨论】:

        【解决方案3】:

        使用collections.defaultdict 和csv.DictReader

        例如:

        import csv
        import collections
        
        d = collections.defaultdict(list)
        
        with open(filename) as infile:
            reader = csv.DictReader(infile)        
            for row in reader:
                d[row["Emotion"]].append(row["begin"])
        
        print(d)
        

        输出:

        defaultdict(<type 'list'>, {'anger': ['1578'], 'surprise': ['1534', '1534', '1534', '1534'], 'fear': ['1611'], 'anticipation': ['772'], 'disgust': ['772', '1345']})
        

        【讨论】:

        • 这很好用!我刚刚编辑了我的问题:数值可以输出为 整数 而不是字符串吗?
        • 一定要用d[row["Emotion"]].append(int(row["begin"]))
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 2011-07-30
        • 1970-01-01
        • 1970-01-01
        • 2020-10-21
        相关资源
        最近更新 更多