【问题标题】:How to loop through a text file and find the matching keywords in Python3如何遍历文本文件并在 Python3 中找到匹配的关键字
【发布时间】:2019-07-01 13:31:41
【问题描述】:

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

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

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

   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'
 ...

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案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
    

    【讨论】:

    • 谢谢!很抱歉,我不太了解回报。你让我很开心!
    • 您好,我还有一个问题。如果用户定义了一个很长的列表,比如说一个列表中有 2000 个单词,那么函数的性能会下降吗?
    • @LiuYu 这个算法的执行时间显然取决于目标列表和文件的长度。
    • 感谢!我的意思是有没有办法优化性能? For循环很慢。但是你的代码拯救了我的一天!我可能会在稍后处理优化。
    猜你喜欢
    • 2020-10-17
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2013-01-13
    相关资源
    最近更新 更多