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!!!

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.