[英]How to extract text from log files in Python
我在網上找到了一些代碼,並嘗試使用它從多個日志文件中提取任何包含錯誤一詞的文本行。 我能夠讀取路徑中的文件並將它們輸出到屏幕上,但實際上無法提取其中包含“錯誤”的行。
我從在線搜索中收集的代碼如下。 運行代碼時,會顯示所有 .log 文件並創建輸出文件,但會列出實際文件名而不是我需要的行。 在我擁有的九個 .log 文件中,我應該收到 5 行包含錯誤。 我確實找到了從 PDF 中提取信息的信息,但從我在網上看到的內容來看,它與我想要做的完全不同。
每個月大約 4-5 次,我們手動搜索 10-50 個 .log 文件以查找錯誤,我希望能夠將所有日志轉儲到一個文件夾中並運行 python 腳本以非常快速地找到錯誤。 我會以錯誤的方式解決這個問題嗎?
import os
# defining location of parent folder
BASE_DIRECTORY = '/pending/PHS'
output_file = open('/pending/PHS/output.txt', 'w')
output = {}
file_list = []
# scanning through sub folders
for (dirpath, dirnames, filenames) in os.walk(BASE_DIRECTORY):
for f in filenames:
if 'log' in str(f):
e = os.path.join(str(dirpath), str(f))
file_list.append(e)
for f in file_list:
print(f)
txtfile = open(f, 'r')
output[f] = []
for line in txtfile:
if 'error' in line:
output[f].append(line)
tabs = []
for tab in output:
tabs.append(tab)
tabs.sort()
for tab in tabs:
output_file.write(tab + '\n')
output_file.write('\n')
for row in output[tab]:
output_file.write(row + '')
output_file.write('\n')
output_file.write('----------------------------------------------------------\n')
第一個評論。 使用with
語句來處理 IO 文件是一種很好的做法,該語句將在此類語句的末尾自動關閉它們。
with Open(txtfile, 'r') as txt:
list_of_lines = txt.readlines()
list_of_lines現在已加載到內存中,並且關閉了 txtfile 的讀取流。
如果您自己創建這些日志,並且您知道“錯誤”這個詞完全一樣,並且每個詞都用空格分隔,那么您可以使用str
內置方法.split()
:
only_errors = []
for line in list_of_lines:
if "error" in line.split(" "):
only_errors.append(line)
output[txtfile] = only_errors
str.split() 方法創建一個字符串列表,分隔出現您指定字符的單詞(在本例中為空格,“”); 然后語句if "error" in ["error", "is", "here"]
將評估 True 並繼續將行附加到列表中。 請注意,與您的方法的唯一區別是,要xx in yy
使用語句xx in yy
, yy必須是幾個xx對象的容器,而不是xx的相同類型(在您的示例中,它們都是字符串)。
就個人而言,我經常使用這個系統。
regedit 模塊re是您正在尋找的更復雜的字符串模式匹配,但我會給您一些谷歌搜索和指向其文檔的鏈接
Fuzzywuzzy是另一種使用 Levenshtein 距離的字符串匹配選項
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.