使用Python編寫提取日誌中的中文的指令碼的方法

來源:互聯網
上載者:User
由於工作需要在一大堆日誌裡面提取相應的一些固定字元,如果單純靠手工取提取,資料量大,勞心勞力,於是自然而然想到了用Python做一個對應的提取工具,代替手工提取的繁雜,涉及中文字元,Regex不好匹配,但不是不可以實現,這個以後最佳化時再說。

需求描述:

一個父目錄中存在多個子檔案夾,子檔案夾下有多個txt形式化的Log日誌,要求從所有地方Log日誌中找出CardType=9, CardNo=0時的CardID的值,並將其統計儲存到一個文字檔中,要求CardID不能夠重複。

需求解析:

首先擷取所有的Log日誌的全路徑,根據路徑分別載入到將各個Log日誌載入到記憶體中進行提取分析,並將結果儲存到給定的文字檔中。

解決方案:

為了儘可能的簡潔通用,這裡使用設定檔作為輸入變數的依據。不多說,上代碼:

設定檔如下:

103檔案夾下有兩個檔案:log1.txt和log2.txt, 內容類別似如下:

Python代碼實現如下:

# -*- coding: utf-8 -*-#!/usr/bin/python# filename: picktools.py# codedtime:2015-3-25import osimport configparser# 遍曆一個目錄,輸出所有檔案名稱def itemsbrowse(path):  for home, dirs, files in os.walk(path):    for filename in files:      yield os.path.join(home, filename)# 給的檔案中尋找對應的字串所在行      def findchars(filename, chars):  file = open(filename, 'r')  for eachline in file:    if eachline.find(chars) >= 0:      yield eachline  file.close()# 添加到指定的檔案def addtofile(filename, mygenerator):  file = open(filename, 'a')   # 追加方式開啟  for line in mygenerator:    file.write(line)  file.close()# 過濾重複的字元行def filter(filename):  mylist = []  file = open(filename, 'r')  for eachline in file:    mylist.append(eachline.strip())  file.close()    file2 = open(os.path.splitext(filename)[0] + '_filter.txt', 'w')  for line in list(set(mylist)):    print(line, file = file2)    #file2.write(line)   file2.close()  def excute():  iniconf = configparser.ConfigParser()  iniconf.read('config.ini')  ifile = iniconf.get('setting', 'ifilepath')  ofile = iniconf.get('setting', 'ofilepath')  chars = iniconf.get('setting', 'searchstr')    for fullname in itemsbrowse(ifile):    mygenerator = findchars(fullname, chars)    addtofile(ofile, mygenerator)      filter(ofile)            if __name__ == '__main__':  excute()


輸出結果:輸出兩個檔案result.txt 和result_filter.txt

心得體會:

1、利用Python去處理一些日常的小任務,可以很方便的完成,相比較C/C++來說,這方面生產力高了不少。

2、本文設計對中文字元的處理,所以使用Regex不太怎麼方便,但不少不可以,後續版本中會添加對正則的支援!

3、由於初學中,所以代碼寫的不夠精鍊簡潔,後續進行再最佳化!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.