打印搜索时出现问题未找到

发布于 2024-11-16 22:50:53 字数 1901 浏览 5 评论 0原文

在下面的代码中,程序从用户处获取字符串数据,并将其转换为 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!!!"

In the code below, the program is getting string data from the user and converting it to ascii and hex and searching all .log and .txt files in a certain directory for the string in plain string, hex, and ascii values. The program prints the line # , the string type found, and the file path if the string is found. However, not only do I want it to print the files if the string is found, I would also like it to print the file and path and string searched for in the files that were searched but not found. I'm a newbie, so please don't be frustrated with the simplicity of the problem. I'm still learning. Thanks. Code below:

 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!!!"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

維他命╮ 2024-11-23 22:50:53

各位,我认为 user706808 想要搜索文件中所有出现的搜索字符串,并且:

  • 对于每个出现的情况,如果在文件中找到字符串,则在每行基础上,打印 lineno,文件路径名
  • 如果在文件中找不到字符串,则在每个文件的基础打印文件路径名(但不是内容)和搜索字符串。
    最简单的方法是在关闭文件或路径名脱离上下文之前,保留出现次数 (nMatches) 的布尔(或整数)跟踪,然后在末尾打印无匹配消息(如果 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”。)

Folks, I think user706808 wants to search for all occurrences of searchstring in file and:

  • for each occurrence if string IS found in file, then on a per-LINE basis, print lineno, file pathname
  • if string is NOT found in file, then on a per-FILE basis print file pathname (but not the contents) and searchstring.
    Easiest way to do that is keep a boolean (or int) track of occurrences (nMatches), then print no-match-message at the end (if nMatches is 0 or False) before you close the file or the pathname goes out of context.

Can you confirm? Assuming that's what you want,
all you need to change is to split up this megaline of code...

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

into...

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

Sound good?

By the way you can now simply refer to fileinput.filename() as 'curPathname'.

(Also you might like to abstract the functionality into a function find_occurrences(searchstring,pathname) which returns int or Boolean 'nOccurrences'.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文