1

让我在python中有以下类:

class Word:
def __init__(self, _lemma, _frequency):
    self.lemma = str(_lemma)
    self.frequency = int(_frequency) 

现在我想创建一个类的集合,当一个对象被添加到集合Word时,它包含以下逻辑:Wordword1

  • 如果集合包含一个Word对象wordword.lemma = word1.lemma那么word.frequency = word.frequency + word1.frequency
  • 否则添加word1到收藏

我该怎么做?


以前我使用列表来检查列表是否包含Word与. 但是该方法在集合中添加 n 具有 O(n^2) 复杂性。lemmaword1.lemmaword

from Word import Word

class Corpus:

    def __init__(self, _name, _total_count):
        self.name = str(_name)
        self.total_count = int(_total_count)
        self.words = []

    def add(self, _word):

        find_word = [index for index, word in enumerate(self.words) if word.lemma == _word.lemma]  # O(n)
        if len(find_word) == 0:
            self.words.append(Word(_word.lemma, _word.frequency))
        else:
            self.words[find_word[0]].frequency = self.words[find_word[0]].frequency + _word.frequency
4

2 回答 2

3

你可以通过使用字典而不是列表来轻松地做到这一点,使用 word.lemma 作为键:

def add(self, _word):
    if _word.lemma not in self.words:
        self.words[_word.lemma] = _word
    else:
        self.words[_word.lemma].frequency += _word.frequency

一个不方便的是它重复了引理信息......


如果使用Word类不是强制性的,您可以使用将频率(值)与引理(键)相关联的defaultdict(默认值为 0):

class Corpus:
    def __init__(...):
        ...
        self.words = defaultdict(lambda: 0)

    def add(self, lemma, frequency):
        self.words[lemma] += frequency
于 2019-03-13T16:03:27.207 回答
2

您的措辞可能会让熟悉 Python 的社区成员感到困惑。我认为您使用“字典”术语作为域模型的一部分,而不是 Python 中的数据结构。

如果你真的需要WordCorpus类 - 你应该继续使用这样的代码:

from collections import defaultdict


class Word:

    def __init__(self, lemma: str, frequency: int):
        self.lemma = lemma
        self.frequency = frequency

    def __eq__(self, other):
        return self.lemma == other.lemma

   def __hash__(self):
       return hash(self.lemma)


class Corpus:

    def __init__(self):
        self.words = defaultdict(0)

    def add(self, word: Word):
        self.words[word] += word.frequency

要点是:

  1. 类型提示的使用
  2. dict查找(例如)如何'b' in {'a': 23, 'b': 24}工作 -何时使用 hash() 调用 __eq__?
  3. defaultdict用法
  4. __eq____hash__使用

我强烈建议您考虑是否真的想将Word实例存储在Corpus.

于 2019-03-13T16:58:18.040 回答