How to loop through a text file and find the matching keywords in Python3

99封情书 提交于 2020-01-11 13:30:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!