I am attempting to write this code which can act as an index of sorts to sift through text files and return the occurrences of strings and which line they were on. I'm getting closer, but I've run into an issue with my iteration and I can't figure out what to do.
def index(fileName, wordList):
infile = open(fileName,'r')
i = 0
lineNumber = 0
while True:
for line in infile:
lineNumber += 1
if wordList[i] in line.split():
print(wordList[i], lineNumber)
i += 1
lineNumber = 0
fileName = 'index.txt'
wordList = eval(input("Enter a list of words to search for: \n"))
index(fileName,wordList)
I filled my .txt file with generic terms so it looks like this:
bird
bird
dog
cat
bird
When I feed a list of strings such as:
['bird','cat']
I get the following output:
Enter a list of words to search for:
['bird','cat']
bird 1
bird 2
bird 5
So it is giving me the term and line number for the first string in the list, but it isn't continuing on to the next string. Any advice? If I could possibly optimize the output to contain the line numbers to a single print that would appreciated.