Вы можете использовать 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)