2

在下面的代码中,程序从用户那里获取字符串数据并将其转换为 ascii 和 hex,并在某个目录中的所有 .log 和 .txt 文件中搜索纯字符串、十六进制和 ascii 值的字符串。程序打印 # 行、找到的字符串类型以及找到字符串的文件路径。但是,如果找到字符串,我不仅希望它打印文件,我还希望它打印在搜索但未找到的文件中搜索的文件和路径和字符串。我是新手,所以请不要对问题的简单性感到沮丧。我还在学习。谢谢。下面的代码:

 elif searchType =='2':
      print "\nDirectory to be searched: " + directory
      print "\nFile result2.log will be created in: c:\Temp_log_files."
      paths = "c:\\Temp_log_files\\result2.log"
      temp = file(paths, "w")
      userstring = raw_input("Enter a string name to search: ")
      userStrHEX = userstring.encode('hex')
      userStrASCII = ''.join(str(ord(char)) for char in userstring)
      regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
      goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")


      def walk_dir(directory, extensions=""):
          for path, dirs, files in os.walk(directory):
             for name in files:
                if name.endswith(extensions):
                   yield os.path.join(path, name)

      whitespace = re.compile(r'\s+')
      for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
          result = regex.search(whitespace.sub('', line))
          if result:
              template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
              output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

              print output
              temp.write(output)
              break
          elif not result:
              template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
              output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

              print output
              temp.write(output)

      else:          
          print "There are no files in the directory!!!"
4

1 回答 1

1

伙计们,我认为 user706808 想要搜索文件中所有出现的 searchstring 并且:

  • 对于每次出现,如果在文件中找到字符串,则在每行的基础上,打印 lineno,文件路径名
  • 如果在文件中找不到字符串,则基于每个文件打印文件路径名(但不是内容)和搜索字符串。最简单的方法是保持布尔(或整数)跟踪事件(nMatches),然后在关闭文件或路径名脱离上下文之前在末尾打印 no-match-message(如果 nMatches 为 0 或 False) .

你确定吗?假设这就是您想要的,您需要更改的只是拆分这个庞大的代码...

for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):

进入...

for curPathname in walk_dir(directory, (".log", ".txt")):
    nOccurrences = 0
    for line in fileinput.input(curPathname):
        result = regex.search(whitespace.sub('', line))
        if result:
            ...
            nOccurrences += 1  # ignores multiple matches on same line 
        # You don't need an 'elif not result' line, since that should happen on a per-file basis
    # Only get here when we reach EOF
    if (nOccurrences == 0):
        NOW HERE print the "not found" message, for curPathname
    # else you could print "found %d occurrences of %s in ..."

听起来不错?

顺便说一句,您现在可以简单地将 fileinput.filename() 称为“curPathname”。

(您也可能希望将功能抽象为一个函数 find_occurrences(searchstring,pathname),它返回 int 或布尔值 'nOccurrences'。)

于 2011-06-24T19:11:19.020 回答