Переписать функцию подсчета слов как ООП в Python 3 - PullRequest
0 голосов
/ 05 февраля 2019

Я написал простую функцию для подсчета вхождений слов в предложении или фразе.

def count(phrase):
    phrase = phrase.lower()    
    lst = phrase.split()
    dct = dict()
    for word in lst:
        if word not in dct:
            dct[word] = 1
        else:
            dct[word] += 1
    return dct

Обратите внимание, что сейчас меня не интересуют пунктуация, числа или стоп-слова.

Я хочу написать класс, чтобы взять объект и сделать то же самое.,Вот что у меня есть, но теперь я застрял в том, как передать список в цикл, который считает и создает словарь:

class Count:
    dct = dict()
    def __init__(self, phrase):
         self.phrase = phrase
    def lst(self):
        return self.phrase.lower().split()

Ответы [ 2 ]

0 голосов
/ 05 февраля 2019

Просто учтите, что для этого вы можете использовать collections.Counter;может быть, вы уже знаете это, но я все равно добавлю эту опцию сюда.

>>> import collections

>>> phrase = "What I want to do is write a class to take an object and do the same thing. Here's what I have so far, but now I'm stuck on how to pass the list on to the loop that counts and creates the dictionary."
>>> c = collections.Counter(phrase.lower().split())
>>> for k, v in c.most_common():
...     print(v, k)

4 to
4 the
2 what
2 i
2 do
2 and
2 on
1 want
1 is
1 write
1 a
1 class
1 take
1 an
1 object
1 same
1 thing.
1 here's
1 have
1 so
1 far,
1 but
1 now
1 i'm
1 stuck
1 how
1 pass
1 list
1 loop
1 that
1 counts
1 creates
1 dictionary.

Нет большого преимущества в том, чтобы обернуть это в классе, но у вас может быть что-то простое, подобное подклассам Counter:

import collections
import string

class MyCounter(collections.Counter):
    def __init__(self, phrase):
        # do some preprocessing, for example removing puntuation
        phrase = ''.join(
            c.lower()
            for c in phrase
            if c not in string.punctuation)

        super().__init__(phrase.split())

Использование будет таким же, как и раньше:

>>> mc = MyCounter(phrase)         # 'lower' and 'split' is done inside
>>> for k, v in mc.most_common():
...     print(v, k)

4 to
4 the
2 what
2 i
2 do
2 and
2 on
1 want
1 is
1 write
1 a
1 class
1 take
1 an
1 object
1 same
1 thing
1 heres
1 have
1 so
1 far
1 but
1 now
1 im
1 stuck
1 how
1 pass
1 list
1 loop
1 that
1 counts
1 creates
1 dictionary
0 голосов
/ 05 февраля 2019

Вы можете использовать defaultdict для удобства.

from collections import defaultdict as ddict
class Count:
    def __init__(self, phrase):
         self.phrase = phrase
         self.dct = ddict(int)
    def lst(self):
        return self.phrase.lower().split()

    # you can do it this way
    def make_dict(self):
        lst_words = self.lst()
        for word in lst_words:
            self.dct[word] += 1

c = Count("What I want to do is write a class to take an object and do the same thing. Here's what I have so far, but now I'm stuck on how to pass the list on to the loop that counts and creates the dictionary")
c.make_dict()     # make a dictonary out of words
c.dct             # display the contents stored in the dict

Вывод:

defaultdict(int,
            {'what': 2,
             'i': 2,
             'want': 1,
             'to': 4,
             'do': 2,
             'is': 1,
             'write': 1,
             'a': 1,
             'class': 1,
             'take': 1,
             'an': 1,
             'object': 1,
             'and': 2,
             'the': 4,
             'same': 1,
             'thing.': 1,
             "here's": 1,
             'have': 1,
             'so': 1,
             'far,': 1,
             'but': 1,
             'now': 1,
             "i'm": 1,
             'stuck': 1,
             'on': 2,
             'how': 1,
             'pass': 1,
             'list': 1,
             'loop': 1,
             'that': 1,
             'counts': 1,
             'creates': 1,
             'dictionary': 1})

Обновление: благодаря любезности Roelant есть еще один способ сделать то же самое, используя Counter.

from collections import Counter
class Count:
    def __init__(self, phrase):
         self.phrase = phrase
         self.dct = None
    def lst(self):
        return self.phrase.lower().split()

    # you can do it this way also.
    def make_dict(self):
        lst_words = self.lst()
        self.dct = Counter(lst_words)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...