Jorgan Jorgan - 15 days ago 6
Python Question

Algorithm to make Python index words by line number (from text file)?

So my homework question is to have function lineIndex index words from a text file and return the list of line numbers for each word in the text file. The whole output has to be returned in a dictionary.

For example here is what it is in the text file:

I have no pride
I have no shame
You gotta make it rain
Make it rain rain rain


My professor wants the output to look like this:

{'rain': [2, 3], 'gotta': [2], 'make': [2], 'it': [2, 3],
'shame': [1], 'I': [0, 1], 'You': [2], 'have': [0, 1], 'no': [0,
1], 'Make': [3], 'pride': [0]}


For example: the word 'rain' is in lines #2 and #3. (First line always starts from zero)

Here is my code so far, but I need help on the algorithm for this.

def lineIndex(fName):
d = {}
with open(fName, 'r') as f:

#algorithm goes here

print(lineIndex('index.txt'))

Answer

My first time writing something in Python, but this works:

def lineIndex(fName):
    d = {}
    with open(fName, 'r') as f:       
        content = f.readlines()
        lnc = 0
        result = {}
        for line in content:
            line = line.rstrip()
            words = line.split(" ")
            for word in words:
                tmp = result.get(word)
                if tmp is None:
                    result[word] = []
                if lnc not in result[word]:
                    result[word].append(lnc)

            lnc = lnc + 1

        return result

print(lineIndex('index.txt'))