2017-09-26 5 views
0

このコードは、検索中のファイルに一致する文字列を出力します文字列が繰り返し存在する場合、巨大なリストで終わる)。私はリストと一致する文字列が何回一致するかを知りたいだけです。私はどの文字列が一致するかを知りたいので、True/Falseの解決法は機能しません。しかし、私はそれらが一致する場合、それぞれ一度だけリストされています。私はパターン= '|' .join(キーワード)の部分がやっていることを本当に理解していません - ファイルを一致させるために他の人のコードから取得しましたが、必要な場合はわかりません。あなたの助けに感謝します。Python:文字列が見つかった場合、その文字列の検索を停止し、次の文字列を検索して一致する文字列を出力します。

# declares the files used 
filenames = ['//Katie/Users/kitka/Documents/appreport.txt', '//Dallin/Users/dallin/Documents/appreport.txt' , 
      '//Aidan/Users/aidan/Documents/appreport.txt'] 

# parses each file 
for filename in filenames: 
    # imports the necessary libraries 
    import os, time, re, smtplib 
    from stat import * # ST_SIZE etc 

    # finds the time the file was last modified and error checks 
    try: 
     st = os.stat(filename) 
    except IOError: 
     print("failed to get information about", filename) 
    else: 
     # creates a list of words to search for 
     keywords = ['LoL', 'javaw'] 
     pattern = '|'.join(keywords) 

     # searches the file for the strings in the list, sorts them and returns results 
     results = [] 
     with open(filename, 'r') as f: 
      for line in f: 
       matches = re.findall(pattern, line) 
       if matches: 
        results.append((line, len(matches))) 

     results = sorted(results) 

     # appends results to the archive file 
     with open("GameReport.txt", "a") as f: 
      for line in results: 
       f.write(filename + '\n') 
       f.write(time.asctime(time.localtime(st[ST_MTIME])) + '\n') 
       f.write(str(line)+ '\n') 

答えて

0

未テストですが、これはうまくいくはずです。これはどの単語が見つかったのかを追跡するだけで、どの単語が見つからなかったのかを把握しています。のファイル。私はそれがあなたが望んだものかどうか分からなかった。

​​

EDIT

あなたは、私は(ファイル名、キーワード)タプルの集合を維持することをお勧めしたい、キーワードがどのファイル中に存在しているのを追跡する場合:

filenames = [...] 
keywords = ['LoL', 'javaw'] 
found = set() 

for filename in filenames: 
    with open(filename, 'rt') as f: 
     for line in f: 
      for keyword in keywords: 
       if keyword in line: 
        found.add((filename, keyword)) 

for filename, keyword in found: 
    print('Found the word "{}" in the file "{}"'.format(keyword, filename)) 
+0

キーワードが見つかったファイルを教えてください。ありがとうございます。これは私の元のコードよりもはるかに効率的で、動作するようです。私はもう少しテストをします。ありがとう! – Stefany

関連する問題