-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathex05e.py
More file actions
executable file
·45 lines (38 loc) · 1.21 KB
/
ex05e.py
File metadata and controls
executable file
·45 lines (38 loc) · 1.21 KB
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
#!/usr/bin/env python
"""
Write a function `wordcount(filename)` that reads a text file and
returns a dictionary, mapping words into occurrences (disregarding
case) of that word in the text. For the purposes of this
exercise, a ``word'' is defined as a sequence of letters and the
character ``-'', i.e., ``e-mail'' and ``more-or-less'' should both
be counted as a single word.
"""
import string
def wordcount(filename):
"""
Read `filename` and return a dictionary mapping each word into the
corresponding count of occurrences within the contents of
`filename`.
"""
# read text from file
fd = open(filename, 'r')
rawtext = fd.read()
fd.close()
# split into list of words
count = {}
for word in rawtext.split():
# convert to lowercase
lcword = word.lower()
# remove non-alphabetic characters
cleanword = lcword.strip(string.punctuation)
# count
if cleanword not in count:
count[cleanword] = 0
count[cleanword] += 1
return count
if __name__ == '__main__':
wc = wordcount('lorem_ipsum.txt')
assert wc['and'] == 3
assert wc['more-or-less'] == 1
assert wc['their'] == 2
assert wc['infancy'] == 1