【问题标题】:How to search and retrieve whole lines from a txt file using Keyword如何使用关键字从 txt 文件中搜索和检索整行
【发布时间】:2015-07-01 11:29:42
【问题描述】:
searchfile =open('test.txt','r')
    for line in searchfile:
        if line in array: print line
    searchfile.close() 

搜索有效,除了我有一个包含简单单词的关键字.txt 文档,例如“绿色、蓝色等”(都在他们自己的行上),然后当我使用这个时,我有一个带有文本的文档,例如“我的衬衫是绿色的”代码它不会找到任何东西,但如果我将 txt 文件中的句子更改为一个单词,它会找到它。我需要它在文档中搜索关键字,然后显示它所在的整行。

【问题讨论】:

    标签: python arrays python-2.7 search arraylist


    【解决方案1】:
    searchfile = open('keywords.txt', 'r')
    infile = open('text.txt', 'r')
    
    for keywords in searchfile:
        for lines in infile:
            if keywords in lines:
               print lines
    

    【讨论】:

      【解决方案2】:

      试试这个

      searchfile = None
      with open('test.txt','r') as f:
          searchfile = f.readlines()
          f.close()
      
      for line in searchfile:
          for word in array:
              if word in line:
                  print line
      

      【讨论】:

        【解决方案3】:

        你可以试试这个:

        searchFile = open('keywords.txt','r')
        file = open('text.txt','r') 
        file1 = file.readlines()  
        file.close()
        for key in searchFile:
            for line in file1:
                if key in Line:
                     print (line)
        

        【讨论】:

          【解决方案4】:

          将关键字设为set,检查该行中是否有任何单词在集合中:

          with open('search.txt','r') as f1, open("keywords.txt") as f2:
              st = set(map(str.rstrip, f2))
              for line in f1:
                  if any(word in st for word in  line.split()):
                      print(line)
          

          如果你不拆分"green" in 'my shirt is greenish' -> True。您还必须考虑标点和大小写。

          如果要忽略大小写并删除标点符号,可以使用str.lowerstr.strip

          from string import punctuation
          with open('search.txt','r') as f1, open("keywords.txt") as f2:
              st = set(map(str.rstrip, f2))
              for line in f1:
                  if any(word.lower().strip(punctuation) in st for word in line.split()):
                      print(line)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-03-22
            • 1970-01-01
            • 2011-01-27
            • 1970-01-01
            • 1970-01-01
            • 2011-10-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多