緣起:
開發人員需要tomcat中一個專案在一個月的訪問請求量,因其他原因只剩下查找tomcat請求日志的方法獲取,剛好最近在學習python,于是就用python摸索了下;
大體思路:1.把相應tomcat的日志檔案拷到有python環境的機器
2.用os.listdir()獲取到目錄下所有檔案名稱的串列,再用for回圈遍歷串列加上字串拼接得到已檔案名的具體路徑
3.用open()讀取檔案,下面代碼中for line in f:是按行讀取txt檔案的內容(一行一行的讀,不會加載全部檔案內容)
4.用count()方法統計以專案為名的關鍵字(字串)
知識點:檔案的讀取和count()方法
Python count() 方法用于統計字串里某個字符出現的次數,可選引數為在字串搜索的開始與結束位置,
count()方法語法:str.count(sub, start= 0,end=len(string))
引數:
- sub -- 搜索的子字串
- start -- 字串開始搜索的位置,默認為第一個字符,第一個字符索引值為0,
- end -- 字串中結束搜索的位置,字符中第一個字符的索引為 0,默認為字串的最后一個位置,
代碼如下(如果檔案過多可以加作業佇列(gevent庫)):
import os # 打開日誌檔案并計數 def read_log(url,keyword): count = 0 with open(url,'r',encoding='utf-8') as f: # 打開檔案 for line in f: # 按行讀取txt檔案 count += line.count(keyword,53,64) # count()方法計數,keyword為傳入的關鍵字(字串) return count path= 'E:\\python\\vscode\\作業\\log\\80\\' dirlist = os.listdir(path) # 獲取path路徑下的所有txt檔案名 sum = 0 for name in dirlist: # 遍歷獲取txt檔案名 url = path + name num = read_log(url,keyword) print(str(name) + ' 檔案中個數為: ' + str(num)) sum += num print('關鍵字總個數: ' + str(sum))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/238895.html
標籤:Python
