【问题标题】:Organization of a dataset in Python在 Python 中组织数据集
【发布时间】:2018-11-25 04:56:04
【问题描述】:

我有一个包含大量习语的 .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']}

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

我最初的想法是尝试使用以下代码拆分逗号:

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

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

我想获得一些关于组织数据的最佳方法的建议?

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    Python 有 an entire module 专门用于处理 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"],
    #  ...
    # ]
    

    您现在可以按照自己的喜好对数据进行排序或组织。

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2016-11-06
      • 2013-04-29
      • 2020-01-18
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多