2017-09-26 139 views
0

此代碼每次在正在搜索的文件中輸出一次匹配的字符串(所以我如果字符串重複出現,最終會得到一個巨大的列表)。我只想知道我的列表中的字符串是否匹配,而不是匹配多少次。我確實想知道哪些字符串匹配,所以True/False解決方案不起作用。但我只希望他們每次都列出一次,如果他們匹配的話。我不太瞭解pattern ='|'.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

未經測試,但這應該工作。請注意,這隻跟蹤找到哪些單詞,而不是找到哪個單詞,其中的文件是。我無法弄清楚這是不是你想要的。

​​

編輯

如果你想跟蹤哪些關鍵字存在於文件,那麼我建議你保持一組(文件名,關鍵詞)元組:

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