2

以下のコードでは、プログラムはユーザーから文字列データを取得し、ASCII および 16 進数に変換し、特定のディレクトリ内のすべての .log および .txt ファイルをプレーン文字列、16 進数、および 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を検索したいと考えています。

  • 文字列がファイル内で見つかった場合は、発生するたびに、LINEごとに、lineno、filepathnameを出力します。
  • 文字列がファイルに見つからない場合は、ファイルごとにファイルのパス名(内容は除く)と検索文字列を出力します。これを行う最も簡単な方法は、ブール(またはint)の発生(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 に答える