首页 > 解决方案 > 在 Python 中组织数据集

问题描述

我有一个包含大量习语的 .csv 数据集。每行包含我想分隔的三个元素(用逗号分隔):

1) 索引号 (0,1,2,3...)

2) 成语本身

3)如果成语是肯定的/否定的/中性的

这是 .csv 文件的一个小示例:

0,"I did touch them one time you see but of course there was nothing doing, he wanted me.",neutral

1,We find that choice theorists admit that they introduce a style of moral paternalism at odds with liberal values.,neutral

2,"Well, here I am with an olive branch.",positive

3,"Its rudder and fin were both knocked out, and a four-foot-long gash in the shell meant even repairs on the bank were out of the question.",negative

如您所见,有时成语会包含引号,而有时则不会。但是,我认为这不会很难排序。

我认为在 Python 中组织它的最佳方法是通过字典,如下所示:

example_dict = {0: ['This is an idiom.', 'neutral']}

那么如何将每一行分成三个不同的字符串(基于逗号),然后使用第一个字符串作为键号,最后两个作为字典中的相应列表项?

我最初的想法是尝试用这段代码分割逗号:

for line in file:    
    new_item = ','.join(line.split(',')[1:])

但它所做的只是删除一行中第一个逗号之前的所有内容,而且我认为通过它进行大量迭代并不是有效的。

我想就组织这样的数据的最佳方法获得一些建议?

标签: pythoncsvdictionary

解决方案


Python 有一个专门用于处理文件的完整模块。csv在这种情况下,您可以使用它从文件中创建列表列表。现在让我们调用您的文件idioms.csv

import csv
with open('idioms.csv', newline='') as idioms_file:
    reader = csv.reader(idioms_file, delimiter=',', quotechar='"')
    idioms_list = [line for line in reader]

# Now you have a list that looks like this:
# [[0, "I did touch them...", "neutral"],
#  [1, "We find that choice...", "neutral"],
#  ...
# ]

您现在可以对数据进行排序或按您喜欢的方式组织数据。


推荐阅读