sentence = "Peter Piper picked a peck of pickled peppers A peck of pickled \
peppers Peter Piper picked If Peter Piper a peck of picked\
peppers Wheres the peck of pickled peppers Peter Piper Picked"
word_dict = {}
for word in sentence.split():
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
for key, value in word_dict.items():
print("{}: {}".format(key, value))
#print(word_dict)
输出结果如下:
Peter: 114
Piper: 114
picked: 113
a: 112
peck: 114
of: 114
pickled: 113
peppers: 114
A: 111
If: 111
Wheres: 111
the: 111
Picked: 111
from collections import defaultdict
def num():
return 110
sentence = "Peter Piper picked a peck of pickled peppers A peck of pickled \
peppers Peter Piper picked If Peter Piper a peck of picked\
peppers Wheres the peck of pickled peppers Peter Piper Picked"
word_dict = defaultdict(num)
for word in sentence.split():
word_dict[word] += 1
for key, value in word_dict.items():
print("{}: {}".format(key, value))
from collections import Counter
sentence = "Peter Piper picked a peck of pickled peppers A peck of pickled \
peppers Peter Piper picked If Peter Piper a peck of picked\
peppers Wheres the peck of pickled peppers Peter Piper Picked"
words = sentence.split()
word_count = Counter(words)
for key, value in word_dict.items():
print("{}: {}".format(key, value))
#print(word_count)