Reputation: 89
You will implement function index() that takes as input the name of a text file and a list of words. For every word in the list, your function will find the lines in the text file where the word occurs and print the corresponding line numbers (where the numbering starts at 1). You should open and read the file only once.
I have been only able to count the occurrence once.
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]))
Output :index('raven.txt',['raven'])
raven 1,
Desired Output : index('raven.txt',['raven'])
raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 12(No of lines it appear)
Upvotes: 0
Views: 1939
Reputation: 11
going over the same problem probably.. i wrote the below..
def index(filename, lst):
infile = open(filename, 'r')
content = infile.readlines()
infile.close()
for word in lst:
print(word, end = '\t')
for line in range(len(content)):
if word in content[line]:
print(line+1, end= ' ')
print()
index('raven.txt', ['raven'])
Upvotes: 1
Reputation: 3157
Not tested but It should work
def index(filename, words):
with open(filename, "r") as f:
for i, line in enumerate(f):
for word in words:
if word in line:
return "%s at line %i" % (word, i + 1)
print index("some_filename", ["word1", "word2"])
Or to avoid nested for loop :
def index(filename, words):
with open(filename, "r") as f:
for line, word in itertools.product(enumerate(f), words):
if word in line[1]:
return "%s at line %i" % (word, line[0] + 1)
print index("some_filename", ["word1", "word2"])
And using list comprehension :
def index(filename, words):
with open(filename, "r") as f:
return "\n".join("%s at line %i" % (word, line[0] + 1) for line, word in itertools.product(enumerate(f), words) if word in line[1])
print index("some_filename", ["word1", "word2"])
Upvotes: 0
Reputation: 2505
How about this example:
File1.txt
Y
x
u
d
x
q
Code:
word='x'
i = 0
with open('file1.txt', 'r') as file:
for line in file:
i = i +1
if word in line:
print(i)
print('Found It')
In this example you read in a file, and look through it line by line. In every line you look if a word is presend. If that is the case we print something on the screen.
Edit:
Or in a definition it would be:
filename='file1.txt'
word='x'
def index(filename, word):
i = 0
with open(filename, 'r') as file:
for line in file:
i = i +1
if word in line:
print(i)
print('Found It')
index(filename, word)
Upvotes: 0