【问题标题】:Creating a list of objects from a dictionary从字典创建对象列表
【发布时间】:2017-02-07 13:35:36
【问题描述】:

首先,我有一个计算文本文件中单词的函数,以及一个根据该文本文件中单词出现次数创建字典的程序。该程序是

def counter (AllWords):
    d = {}
    for word in AllWords:
        if word in d.keys():
            d[word] = d[word] + 1
        else:
            d[word] = 1
    return d;

f = open("test.txt", "r")
AllWords = []

for word in f.read().split():
    AllWords.append(word.lower())

print(counter(AllWords))

现在给定那个字典,我想创建一个对象列表,这样对象将有两个实例变量,单词(字符串)和它出现的次数(整数)。任何帮助表示赞赏!

【问题讨论】:

    标签: python-3.x class object


    【解决方案1】:

    怎么样:

    list(d.items())
    

    它将创建一个元组列表,例如:

    [('Foo',3),('Bar',2)]
    

    或者你可以定义你自己的类:

    class WordCount:
    
        def __init__(self,word,count):
            self.word = word
            self.count = count
    

    并使用列表推导:

    [WordCount(*item) for item in d.items()]
    

    所以在这里你创建了一个WordCount 对象的列表。

    尽管如此,您的counter(..) 方法实际上是不必要的:Python 已经有一个Counter

    from collections import Counter
    

    可以说是“一本有东西的字典”:你可以简单地构造它:

    from collections import Counter
    
    Counter(allWords)
    

    【讨论】:

    • 嗨,我想使用定义我自己的类方法,但我不太确定发生了什么。假设我有一本字典 d = { "this" : 5, "is" : 7, "wrong" : 8}
    • 嗨,我想使用定义我自己的类方法,但我不太确定发生了什么。假设我有一本字典 d = { "this" : 5, "is" : 7, "wrong" : 8} 我们定义了我们的类 class WordCount(): def __init__(self, word, count): self.word = word self.count = count list_obj = [WordCount(*item) for item in d.items()] print(list_obj) 但这不会产生列表吗?很抱歉,我刚开始学习类和对象,很难得到它。
    • list_obj 是一个列表,WordCount 项目的列表。它是由list comprehension 构造的。您可以使用type(list_obj)查看类型。
    【解决方案2】:

    无需重新发明轮子来计数项目。

    一个准单线器来完成所有繁重的工作怎么样?当然使用collections.Counter 和强大的str.split

    import collections
    
    with open("text.txt") as f:
        c = collections.Counter(f.read().split())
    

    现在c 包含对:单词,单词出现次数

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多