13.3 단어 히스토그램
이 절을 진행하려면 이전 연습문제를 풀어야 한다. 해법은 http://thinkpython2.com/code/analyze_book1.py에서 받을 수 있다. 또한, 이 절에서는 http://thinkpython2.com/code/emma.txt도 필요할 것이다.
다음 프로그램은 파일을 읽어 들여서 파일의 단어에 대한 히스토그램을 구축한다.
import string
def process_file(filename):
hist = dict()
fp = open(filename)
for line in fp:
process_line(line, hist)
return hist
def process_line(line, hist):
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(string.punctuation + string.whitespace)
word = word.lower()
hist[word] = hist.get(word, 0) + 1
hist = process_file('emma.txt')