【问题标题】:Creating a dictionary of dictionaries from csv file从 csv 文件创建字典字典
【发布时间】:2016-09-03 00:01:23
【问题描述】:

您好,我正在尝试编写一个函数,classify(csv_file),它从 csv 文件创建一个默认的字典字典。第一个“列”(每行中的第一项)是字典中每个条目的键,然后第二个“列”(每行中的第二项)将包含值。

但是,我想通过调用两个函数(按此顺序)来更改

  1. trigram_c(string):在字符串中创建一个默认的 trigram 计数字典(即值)
  2. normal(tri_counts):获取 trigram_c 的输出并对计数进行归一化(即将每个 trigram 的计数转换为数字)。

因此,我的最终输出将是一本字典:

{value: {trigram1 : normalised_count, trigram2: normalised_count}, value2: {trigram1: normalised_count...}...} and so on

我当前的代码如下所示:

def classify(csv_file):
    l_rows = list(csv.reader(open(csv_file)))
    classified = dict((l_rows[0], l_rows[1]) for rows in l_rows)

例如,如果 csv 文件是:

Snippet1, "It was a dark stormy day"
Snippet2, "Hello world!"
Snippet3, "How are you?"

最终输出类似于:

{Snippet1: {'It ': 0.5352, 't w': 0.43232}, Snippet2: {'Hel' : 0.438724,...}...} and so on.

(当然,不只是两个三元组计数,并且出于示例的目的,这些数字只是随机的)。

任何帮助将不胜感激!

【问题讨论】:

    标签: string python-3.x csv dictionary count


    【解决方案1】:

    首先,请检查分类功能,因为我无法运行它。这里更正版本:

    import csv
    
    def classify(csv_file):
        l_rows = list(csv.reader(open(csv_file)))
        classified = dict((row[0], row[1]) for row in l_rows)
        return classified
    

    它返回带有第一列键的字典,值是第二列的字符串。
    因此,您应该迭代每个字典条目并将其值传递给 trigram_c 函数。我不明白你是如何计算三元组计数的,但例如,如果你只计算字符串中出现的三元组的数量,你可以使用下面的函数。如果要进行其他计数,只需更新 for 循环中的代码即可。

    def trigram_c(string):
        trigram_dict = {}
        start = 0
        end = 3
        for i in range(len(string)-2):
            # you could implement your logic in this loop
            trigram = string[start:end]
            if trigram in trigram_dict.keys():
                trigram_dict[trigram] += 1
            else:
                trigram_dict[trigram] = 1
            start += 1
            end += 1
        return trigram_dict
    

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2012-12-15
      • 2012-01-02
      • 2016-11-22
      • 2016-11-20
      相关资源
      最近更新 更多