How to find on which row of a text file a word is found

Viewed 220

I have a text file containing this:

    Pacemakers, neurotechnology, nanoparticles, and interpretation of medical images - 
    with the combination of knowledge in mathematics, physics, and technology, 
    you can be involved in developing medical technology that can save lives and improve human 
    health.



    Developments in medical technology are going furiously fast and "engineering for health" 
    is becoming increasingly important. As a civil engineer in medical technology, 
    you get to participate in the development of medical science. 
    You create the tools that process data from computed tomography, MRI cameras, and bio-optical 
    sensors into a form that the doctor can interpret; which combines technology with the body's 
    functions and which explores new areas of application in health, environment, and sports.

What I am trying to do is to write a code that will search for a word, and the output will be on which row the code is on. For example, if I want to search for "pacemaker" then the output will be "1" because it's on that row, and so on.

I was thinking maybe the code could look for every "\n" in the file, and whenever it finds it, it increases a counter by 1, so I can keep track of which row. And when the word is found I just return the value of the counter.

I tried something like this:

def find_row(word):
    counter = 0
    with open(self.text,"r",encoding="utf-8") as a_file:
        for line in a_file:
            if word == a_file:
                if keyword == "\n":
                    counter += 1

However, I feel like this logic is completely backward, I really don't know how to proceed from here.

5 Answers

Well everyone is telling you to use enumerate. They aren't wrong but would you like to know what went wrong with your code? It needs a print and the count should go up with every line unconditionally. It also helps to look at every word in the line.

def find_row(word):
    counter = 0
    with open(self.text,"r",encoding="utf-8") as a_file:
        for line in a_file:
            if word in line:
                print(counter)
            counter += 1

That will work on it's own. Sure enumerate will tidy things up but it's nice to know how to do this yourself.

I know you talked about returning. But you also talked about output. These aren’t the same thing. Anyway you can replace print with a return. But that will only tell you the first line number a match is on. Using print will output every line number that has a match.

Which one is correct is difficult to say because your example and description both allow for either.

Use enumerate()

with open(self.text,"r",encoding="utf-8") as a_file:
    for row_number, line in enumerate(a_file, start=1):
        if word in line:
            print(row_number)

You've overcomplicated this. Imagine you have read through the file and stored each line in a list called rows. Using enumerate() to accomplish your goal will be easy.

rows = [row for row in file]
for count,row in enumerate(rows):
    if 'Pacemakers' in row:
        print(count)

There are multiple approaches you can take in this situation

  1. You can line-by-line check if the word exists in the current line:
with open(self.text,"r",encoding="utf-8") as f:
    for index, line in enumerate(f):
        if word in line.lower():    # according to your example, the code shouldn't match the case 
            print(f'Found "{word}" in line {index+1}') # you are counting from 1
  1. You can read the lines once and perform the search on that list if you want to try multiple words, reading from file every time will make your code slower:
with open(self.text,"r",encoding="utf-8") as f:
    lines = f.readlines()  # this method returns list of lines
for index, line in enumerate(lines):
    if word in line.lower():   
        print(f'Found "{word}" in line {index+1}') # you are counting from 1

As proposed there are several ways to do that.

The simpler solution I would do is

lines = open(path,"r",encoding="utf-8").readlines()
for line in lines:
    if(word in line):
        print(lines.index(line) + 1)

or

lines = open(path,"r",encoding="utf-8").readlines()
for line_index in range(len(lines)):
    if(word in lines[line_index]):
        print(line_index + 1)
Related