Issue
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
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.