How To Find A Word In A String In A List? (python)
So im trying to find a way so I can read a txt file and find a specific word. I have been calling the file with myfile=open('daily.txt','r') r=myfile.readlines() that would retu
Solution 1:
def findLines():
myWord = 'someWordIWantToSearchFor'
answer = []
withopen('daily.txt') as myfile:
lines = myfile.readlines()
for line in lines:
if myWord in line:
answer.append(line)
return answer
Solution 2:
withopen('daily.txt') as myfile:
for line in myfile:
if"needle"in line:
print"found it:", line
With the above, you don't need to allocate memory for the entire file at once, only one line at a time. This will be much more efficient if your file is large. It also closes the file automatically at the end of the with
.
Solution 3:
I'm not sure if the suggested answers solve the problem or not, because I'm not sure what the original proposer means. If he really means "words," not "substrings" then the solutions don't work, because, for example,
'cat'in line
evaluates to True if line contains the word 'catastrophe.' I think you may want to amend these answers along the lines of
if word in line.split(): ...
Post a Comment for "How To Find A Word In A String In A List? (python)"