如何遍历文本文件并在Python3中找到匹配的关键字

时间:2019-07-01 13:31:41

标签: python-3.x for-loop

我正在一个项目中定义Python3中的搜索功能。目标是从列表中输出关键字,并从adele.txt中输出包含关键字的句子。

这是用户定义的列表,userlist = ['looking','for','wanna'], adele.txt在github页面上,https://github.com/liuyu82910/search

下面是我的功能。第一个循环是从adele.txt获取所有行的小写字母,第二个循环是在用户列表中获取每个单词的小写字母。我的代码无法正确循环。我想要的是循环显示文本中的所有行,并与列表中的所有单词进行比较。我做错了什么?

   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

这是我当前的结果,它停止循环,我只有一个结果:

Out[122]:
('looking', '->', 'looking for some education\n')

所需的输出为:

'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 个答案:

答案 0 :(得分:1)

这里:

if neword in newline:
    return neword,'->',newline
else:
    return False

您将在第一次迭代中返回(元组或False)。 return的意思是“立即退出此功能”。

简单的解决方案是将所有匹配项存储在列表(或字典等)中并返回:

# 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