【发布时间】: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