Concordance using Python dict
A starting point to make a word concordance. Learn to use dict, the Python map of keys to values.
Size 1.2 kB - File type text/python-sourceFile contents
#
#Comp 171 Standard Python Script Header
#Assignment name: More experience with Python dict dictionary type
#LUC id and Name whonig@luc.edu - Dr. William L. Honig
#Date 8 April 2012
#
#Building a concordance of words
#Another name for dict (dictionary) is a map
#Maps relate one object (the key) to another (the value)
#
#Documentation and help:
# http://anh.cs.luc.edu//python/hands-on/3.1/handsonHtml/dictionaries.html
# http://docs.python.org/dev/py3k/library/stdtypes.html#mapping-types-dict
#
#Questions:
# 1.Can you modify the program to save the line numbers of each line the word is on?
# 2.How would you get the print out to be alphabetized?
#
def countWords():
myFile = open("InputForConcordance.txt", "r")
concord = dict()
for line in myFile:
wordList = line.split()
for word in wordList:
word = word.strip('.,"')
if( word in concord):
concord[word] = concord[word] + 1
else:
concord[word] = 1 #first time we've seen this word
for word in iter(concord):
print( "{0:20}{1:>5}".format(word, concord[word]))
Click here to get the file