gpt4 book ai didi

python - csv 文件的两个特定列的列表字典

转载 作者:行者123 更新时间:2023-11-30 22:05:40 25 4
gpt4 key购买 nike

我正在处理的 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]],....]]}

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

提前致谢!

编辑:

字典值应输出为整数

最佳答案

使用collections.defaultdictcsv.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']})

关于python - csv 文件的两个特定列的列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52926061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com