【问题标题】:How to search for a string in text files?如何在文本文件中搜索字符串?
【发布时间】:2011-06-23 19:49:31
【问题描述】:

我想检查一个字符串是否在文本文件中。如果是,则执行 X。如果不是,则执行 Y。但是,由于某种原因,此代码始终返回 True。任何人都可以看出什么问题吗?

def check():
    datafile = file('example.txt')
    found = False
    for line in datafile:
        if blabla in line:
            found = True
            break

check()
if True:
    print "true"
else:
    print "false"

【问题讨论】:

    标签: python


    【解决方案1】:

    这是另一个。获取绝对文件路径和给定字符串并将其传递给 word_find(),在 enumerate() 方法中对给定文件使用 readlines() 方法,该方法在逐行遍历时给出可迭代计数,最后为您提供line 与匹配的字符串,加上给定的行号。干杯。

      def word_find(file, word):
        with open(file, 'r') as target_file:
            for num, line in enumerate(target_file.readlines(), 1):
                if str(word) in line:
                    print(f'<Line {num}> {line}')
                else:
                    print(f'> {word} not found.')
    
    
      if __name__ == '__main__':
          file_to_process = '/path/to/file'
          string_to_find = input()
          word_find(file_to_process, string_to_find)
    

    【讨论】:

      【解决方案2】:
      found = False
      def check():
      datafile = file('example.txt')
      for line in datafile:
          if "blabla" in line:
              found = True
              break
      return found
      
      if check():
          print "found"
      else:
          print "not found"
      

      【讨论】:

        【解决方案3】:

        你总是得到True的原因已经给出,所以我再提供一个建议:

        如果你的文件不是太大,你可以把它读成一个字符串,然后直接使用它(比每行读取和检查行更容易而且通常更快):

        with open('example.txt') as f:
            if 'blabla' in f.read():
                print("true")
        

        另一个技巧:您可以通过使用mmap.mmap() 创建一个使用底层文件的“类似字符串”的对象(而不是读取内存中的整个文件)来缓解可能的内存问题:

        import mmap
        
        with open('example.txt') as f:
            s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
            if s.find('blabla') != -1:
                print('true')
        

        注意:在 python 3 中,mmap 的行为类似于 bytearray 对象而不是字符串,因此您使用 find() 查找的子序列也必须是 bytes 对象而不是字符串,例如。 s.find(b'blabla'):

        #!/usr/bin/env python3
        import mmap
        
        with open('example.txt', 'rb', 0) as file, \
             mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
            if s.find(b'blabla') != -1:
                print('true')
        

        您还可以在 mmap 上使用正则表达式,例如,不区分大小写的搜索:if re.search(br'(?i)blabla', s):

        【讨论】:

        • 第二种解决方案在我的 python 2.7 中给出的结果与'blabla' in open('example.txt').read() 不同
        • 奇怪,它确实适用于 s.find('blabla')(检查 -1)。我可以发誓它曾经也可以与 in 一起使用...但现在看来 in 仅适用于单个字符...
        • if 'blabla' in open('example.txt').read(): print "true" ==> 在这种情况下我们如何关闭example.txt 文件?
        • @begueradj:关于 mmap 解决方案:您应该使用 find() 方法(参见以前的 cmets),我已经相应地更新了答案。
        • open 一般应该封装在with 语句中:with open(file_name) as fl: return text in fl.read()
        【解决方案4】:

        如果用户想在给定的文本文件中搜索单词。

         fopen = open('logfile.txt',mode='r+')
        
          fread = fopen.readlines()
        
          x = input("Enter the search string: ")
        
          for line in fread:
        
              if x in line:
        
                  print(line)
        

        【讨论】:

          【解决方案5】:

          正如 Jeffrey 所说,您没有检查 check() 的值。此外,您的 check() 函数没有返回任何内容。注意区别:

          def check():
              with open('example.txt') as f:
                  datafile = f.readlines()
              found = False  # This isn't really necessary
              for line in datafile:
                  if blabla in line:
                      # found = True # Not necessary
                      return True
              return False  # Because you finished the search without finding
          

          然后就可以测试check()的输出了:

          if check():
              print('True')
          else:
              print('False')
          

          【讨论】:

            【解决方案6】:

            为此我做了一个小函数。它在输入文件中搜索一个单词,然后将其添加到输出文件中。

            def searcher(outf, inf, string):
                with open(outf, 'a') as f1:
                    if string in open(inf).read():
                        f1.write(string)
            
            • outf 是输出文件
            • inf 是输入文件
            • string 当然是您希望找到并添加到 outf 的所需字符串。

            【讨论】:

              【解决方案7】:

              如何在文件中搜索文本并返回找到该单词的文件路径 (Как искать часть текста в файле и возвращять путь к файлу в котором это слово найдено)

              import os
              import re
              
              class Searcher:
                  def __init__(self, path, query):
                      self.path   = path
              
                      if self.path[-1] != '/':
                          self.path += '/'
              
                      self.path = self.path.replace('/', '\\')
                      self.query  = query
                      self.searched = {}
              
                  def find(self):
                      for root, dirs, files in os.walk( self.path ):
                          for file in files:
                              if re.match(r'.*?\.txt$', file) is not None:
                                  if root[-1] != '\\':
                                      root += '\\'           
                                  f = open(root + file, 'rt')
                                  txt = f.read()
                                  f.close()
              
                                  count = len( re.findall( self.query, txt ) )
                                  if count > 0:
                                      self.searched[root + file] = count
              
                  def getResults(self):
                      return self.searched
              

              在 Main() 中

              # -*- coding: UTF-8 -*-
              
              import sys
              from search import Searcher
              
              path = 'c:\\temp\\'
              search = 'search string'
              
              
              if __name__ == '__main__':
              
                  if len(sys.argv) == 3:
                      # создаем объект поисковика и передаем ему аргументы
                      Search = Searcher(sys.argv[1], sys.argv[2])
                  else:
                      Search = Searcher(path, search)
              
                  # начать поиск
                  Search.find()
              
                  # получаем результат
                  results = Search.getResults()
              
                  # выводим результат
                  print 'Found ', len(results), ' files:'
              
                  for file, count in results.items():
                      print 'File: ', file, ' Found entries:' , count
              

              【讨论】:

              • 如果您对此主题有疑问但本问答未回答,请在右上角提出新问题。
              【解决方案8】:

              这是另一种可能使用 find 函数回答您的问题的方法,它为您提供某物真正所在位置的文字数值

              open('file', 'r').read().find('')
              

              在 find 中写下你要查找的单词 'file' 代表你的文件名

              【讨论】:

                【解决方案9】:

                找到 = 假

                def check():
                    datafile = file('example.txt')
                    for line in datafile:
                        if blabla in line:
                            found = True
                            break
                    return found
                
                if check():
                    print "true"
                else:
                    print "false"
                

                【讨论】:

                  【解决方案10】:

                  两个问题:

                  1. 您的函数不返回任何内容;不显式返回任何内容的函数返回 None(这是错误的)

                  2. True 始终为 True - 您没有检查函数的结果

                  .

                  def check(fname, txt):
                      with open(fname) as dataf:
                          return any(txt in line for line in dataf)
                  
                  if check('example.txt', 'blabla'):
                      print "true"
                  else:
                      print "false"
                  

                  【讨论】:

                    【解决方案11】:

                    您的 check 函数应返回 found 布尔值并使用它来确定要打印的内容。

                    def check():
                            datafile = file('example.txt')
                            found = False
                            for line in datafile:
                                if blabla in line:
                                    found = True
                                    break
                    
                            return found
                    
                    found = check()
                    if found:
                        print "true"
                    else:
                        print "false"
                    

                    第二个块也可以压缩为:

                    if check():
                        print "true"
                    else:
                        print "false"
                    

                    【讨论】:

                    • 以上所有答案都是非常错误的,除了你的。我花了半天的时间来猜测他们验证的答案会发生什么,而这完全是错误的。只有你的对我有用
                    【解决方案12】:
                    if True:
                        print "true"
                    

                    这总是发生,因为 True 总是 True。

                    你想要这样的东西:

                    if check():
                        print "true"
                    else:
                        print "false"
                    

                    祝你好运!

                    【讨论】:

                    • 我明白了,它现在可以工作了。不过对我来说似乎有点奇怪,这意味着 Python 说“一个模块是真的,除非另有说明”。因此,如果我制作一个空模块,它总是正确的吗?有趣:)
                    • 不,一点也不——与模块无关。您只是在检查 True 是否为真,它是真的。
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2010-12-10
                    • 1970-01-01
                    相关资源
                    最近更新 更多