r = ","
x = ""
output = list()
import string
def find_word(filepath,keyword):
doc = open(filepath, 'r')
for line in doc:
#Remove all the unneccessary characters
line = line.replace("'", r)
line = line.replace('`', r)
line = line.replace('[', r)
line = line.replace(']', r)
line = line.replace('{', r)
line = line.replace('}', r)
line = line.replace('(', r)
line = line.replace(')', r)
line = line.replace(':', r)
line = line.replace('.', r)
line = line.replace('!', r)
line = line.replace('?', r)
line = line.replace('"', r)
line = line.replace(';', r)
line = line.replace(' ', r)
line = line.replace(',,', r)
line = line.replace(',,,', r)
line = line.replace(',,,,', r)
line = line.replace(',,,,,', r)
line = line.replace(',,,,,,', r)
line = line.replace(',,,,,,,', r)
line = line.replace('#', r)
line = line.replace('*', r)
line = line.replace('**', r)
line = line.replace('***', r)
#Make the line lowercase
line = line.lower()
#Split the line after every r (comma) and name the result "word"
words = line.split(r)
#if the keyword (also in lowercase form) appears in the before created words list
#then append the list output by the whole line in which the keyword appears
if keyword.lower() in words:
output.append(line)
return output
print find_word("pg844.txt","and")
The goal of this piece of code is to search through a text file for a certain keyword, say "and", then put the whole line in which the keyword is found into a list of type (int,string). The int should be the line number and the string the above mentioned rest whole line.
I'm still working on the line numbering - so no question concerning that yet. But the problem is: The output is empty. Even if I append a random string instead of the line, I don't get any results.
If I use
if keyword.lower() in words:
print line
I get all the desired lines, in which the keyword occurs. But I just can't get it into the output list.
The text file I'm trying to search through: http://www.gutenberg.org/cache/epub/844/pg844.txt