-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathdictogram.py
61 lines (49 loc) · 2.22 KB
/
dictogram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!python
from __future__ import division, print_function # Python 2 and 3 compatibility
class Dictogram(dict):
"""Dictogram is a histogram implemented as a subclass of the dict type."""
def __init__(self, word_list=None):
"""Initialize this histogram as a new dict and count given words."""
super(Dictogram, self).__init__() # Initialize this as a new dict
# Add properties to track useful word counts for this histogram
self.types = 0 # Count of distinct word types in this histogram
self.tokens = 0 # Total count of all word tokens in this histogram
# Count words in given list, if any
if word_list is not None:
for word in word_list:
self.add_count(word)
def add_count(self, word, count=1):
"""Increase frequency count of given word by given count amount."""
# TODO: Increase word frequency by count
def frequency(self, word):
"""Return frequency count of given word, or 0 if word is not found."""
# TODO: Retrieve word frequency count
def print_histogram(word_list):
print('word list: {}'.format(word_list))
# Create a dictogram and display its contents
histogram = Dictogram(word_list)
print('dictogram: {}'.format(histogram))
print('{} tokens, {} types'.format(histogram.tokens, histogram.types))
for word in word_list[-2:]:
freq = histogram.frequency(word)
print('{!r} occurs {} times'.format(word, freq))
print()
def main():
import sys
arguments = sys.argv[1:] # Exclude script name in first argument
if len(arguments) >= 1:
# Test histogram on given arguments
print_histogram(arguments)
else:
# Test histogram on letters in a word
word = 'abracadabra'
print_histogram(list(word))
# Test histogram on words in a classic book title
fish_text = 'one fish two fish red fish blue fish'
print_histogram(fish_text.split())
# Test histogram on words in a long repetitive sentence
woodchuck_text = ('how much wood would a wood chuck chuck'
' if a wood chuck could chuck wood')
print_histogram(woodchuck_text.split())
if __name__ == '__main__':
main()