Personal tools
You are here: Home → Comp 171 Scripting Practicum → Course Materials → Python Materials → Python Programs → Concordance using Python dict
Document Actions

Concordance using Python dict

by Dr. William L. Honig — last modified 2012-04-08 01:29 PM

A starting point to make a word concordance. Learn to use dict, the Python map of keys to values.

Click here to get the file

Size 1.2 kB - File type text/python-source

File 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]))
    
            
« October 2026 »
Su Mo Tu We Th Fr Sa
123
45678910
11121314151617
18192021222324
25262728293031
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: