Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two questions that I need answered. The first one is when I run my code it looks for the first instance of the word that I'm searching for and prints it out, but the line it prints out is one line short of where its suppose to be. So if I looked for the word "life', for example, it would print out the line "number 9" when actually the word is on line 10.

The second problem that I want to figure out is how to find multiple lines that have the word "life" inside my text file. I didn't know if I could use the enumerate module in order to look for multiple lines that have the word "life" and print those lines out. This is what I have so far.

Here's my code:
word = input("Enter the word to search for: ")

line_number = 0
text = open('current_line.txt', 'r') 
for number, line in enumerate(text):
  if word in line:
    line_number = number
    break

text.close()

print(line_number)


What I have tried:

I tried looking online for any resources that help with looking for multiple lines but none of those results were things that I was trying to do.
Posted
Updated 8-Jun-21 0:31am

1) Because numbering starts at zero, not one: Python enumerate(): Simplify Looping With Counters – Real Python[^]

2) Yes, you can. But that code only finds the first one because it exits the loop when it finds a match. If you print the line number instead of the break line, it'll show you them all.
 
Share this answer
 
Comments
adam breslin 8-Jun-21 21:15pm    
Thanks the for the resource it worked, I just bookmarked it. I did what you said and set "start=1" (start equal to 1) right next to the word "text" inside of the enumerate parameters. I also got rid of the break line and now it iterates through the entire text file and looks for all of the words with "life." Thanks for the help
OriginalGriff 9-Jun-21 0:47am    
You're welcome!
I gave you a suggested solution at Why am I getting a key error when I print my dictionary?[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900