问题
I am working on a project to define a search function in Python3. Goal is to output the keywords from a list and the sentence(s) from adele.txt that contain(s) the keywords.
This is a user defined list, userlist=['looking','for','wanna'], adele.txt is on the github page, https://github.com/liuyu82910/search
Below is my function. The first loop is to get all the lines in lowercase from adele.txt, second loop to get the each word in lowercase in userlist. My code is not looping correctly. What I want is to loop all the lines in the text and compare with all the words from the list. What did I do wrong?
def search(list):
with open('F:/adele.txt','r') as file:
for line in file:
newline=line.lower()
for word in list:
neword=word.lower()
if neword in newline:
return neword,'->',newline
else:
return False
This is my current result, it stops looping, I only got one result:
Out[122]:
('looking', '->', 'looking for some education\n')
Desired output would be:
'looking', '->', 'looking for some education'
... #there are so many sentences that contain looking
'looking',->'i ain't mr. right but if you're looking for fast love'
...
'for', -> 'looking for some education'
...#there are so many sentences that contain for
'wanna',->'i don't even wanna waste your time'
...
回答1:
Here:
if neword in newline:
return neword,'->',newline
else:
return False
You are returning (either a tuple or False) on the very first iteration. return means "exit the function here and now".
The simple solution is to store all matches in a list (or dict etc) and return that:
# s/list/targets/
def search(targets):
# let's not do the same thing
# over and over and over again
targets = [word.lower() for word in targets]
results = []
# s/file/source/
with open('F:/adele.txt','r') as source:
for line in source:
line = line.strip().lower()
for word in targets:
if word in line:
results.append((word, line))
# ok done
return results
来源:https://stackoverflow.com/questions/56836617/how-to-loop-through-a-text-file-and-find-the-matching-keywords-in-python3