Hello,

I have been working on this code but I can't seem to make it work. I want to implement function index() that takes as input the name of a text file (as a string) and a list of words. For every word in the list, the function will print the lines in the text file where the word occurs and print the corresponding line numbers (where the numbering starts at 1).

For Example:

index('raven.txt', ['raven', 'mortal', 'dying', 'ghost', 'ghastly', 'evil','demon'])

ghost     9,
dying     9,
demon     122,
evil      99, 106,
ghastly   82,
mortal    30,
raven     44, 53, 55, 64, 78, 97, 104, 111, 118, 120, 

So far my code looks like this:

def index(filename, words):
    infile = open(filename)
    content = infile.readlines()
    infile.close()
    count = {}
for word in words:
    if word in count:
        count[word] += 1
    else:
        count[word] = 1
    for word in count:
        print('{:12}{},'.format(word, count[word]))

This is counting the words in the text file but I want to count the number of lines in which this words occur. HELP!!!

Edited 3 Years Ago by Reverend Jim: Fixed formatting

def index(filename, words):
    infile = open(filename)
    content = infile.readlines()
    infile.close()
    count = {}
for word in words:
    if word in count:
        count[word] += 1
    else:
        count[word] = 1
    for word in count:
        print('{:12}{},'.format(word, count[word]))

You are not truthfull your code can not work: content of file from line 3 is never used after reading in and indention is off at line 6 onwards. Show us real effort.

Edited 6 Years Ago by pyTony: n/a

def index(filename, words):
    infile = open(filename)
    content = infile.readlines()
    infile.close()
    count = {}
for word in words:
    if word in count:
        count[word] += 1
    else:
        count[word] = 1
    for word in count:
        print('{:12}{},'.format(word, count[word]))

Thanks

Edited 6 Years Ago by br0wnm4n: n/a

This article has been dead for over six months. Start a new discussion instead.