Why is my code not looping through the words?

Question:

I need to look for a list of words in a document. However, when I run my code it seems to only iterate over the first word. I know it has something to do with my while(s) loop, but I just can’t seem to get it to work. Also, yes the words are in the document.

How do I apply the code to each word in the list?

file = open('DOG2.txt', 'r')
word = ['cat','dog','Yellow']
s = " "
count=1
for p in word:
    while(s):
      s = file.readline()
      L = s.split()
      if p in L:
          print("Line Number:",file.name,p,count,":",s)

      count+=1
Asked By: B MS

||

Answers:

The main issue was, file operation is a stream operation. Each read operation is monotony increases unless you manually reset it.
To fix your code, at the end of each for p loop, you need to insert file.seek(0).


Here is a better solution that only scan the file once (instead of 3 times):

word = ['cat','dog','Yellow']
count=0
with open('DOG2.txt', 'r') as file:
    for line in file:
        count+=1
        for w in word:
            if w in line.strip().split():
                print("LineNumber:{} {} {} : {}".format(file.name, w, count, line), end="")

Here is an even better solution to enhance the performance when the file and word size are large.

word = {'cat','dog','Yellow'}
count=0
with open('DOG2.txt', 'r') as file:
    for line in file:
        count+=1
        lset = set(line.strip().split())
        if bool(word & lset):
            print("LineNumber:{} {} : {}".format(file.name, count, line), end="")
Answered By: Xin Cheng

When using readline python keeps track of which line it has to read. So, after reading the last line, it does not start from the beginning and returns an empty string '' on calling readline (which also evaluates to false in loop conditions).

In your code, you finish all the lines during the check for the first word. So, what is the solution? Read the line first and check all the words in the L list that you have created. A fix would probably be something like this.

file = open('DOG2.txt', 'r')
word = ['cat','dog','Yellow']
s = " "
while s:
    s = file.readline()
    L = s.split()
    for p in word:
        if p in L:
            print("Line Number:",file.name,p,count,":",s)
    count += 1

Recommendation: You can use for loop to iterate over the lines of a file. For example:

f = open('fn.txt', 'r')
for line in f:
   ...
Answered By: AliBaharni97
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.