由於工作需要在一大堆日志里面提取相應的一些固定字符,如果單純靠手工取提取,數據量大,勞心勞力,於是自然而然想到了用Python做一個對應的提取工具,代替手工提取的繁雜,涉及中文字符,正則表達式不好匹配,但不是不可以實現,這個以后優化時再說。
需求描述:
一個父目錄中存在多個子文件夾,子文件夾下有多個txt形式化的Log日志,要求從所有地方Log日志中找出CardType=9, CardNo=0時的CardID的值,並將其統計存儲到一個文本文件中,要求CardID不能夠重復。
需求解析:
首先獲取所有的Log日志的全路徑,根據路徑分別加載到將各個Log日志加載到內存中進行提取分析,並將結果存儲到給定的文本文件中。
解決方案:
為了盡可能的簡潔通用,這里使用配置文件作為輸入變量的依據。不多說,上代碼:
配置文件如下:
103文件夾下有兩個文件:log1.txt和log2.txt, 內容類似如下:
Python代碼實現如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# -*- coding: utf-8 -*-
#!/usr/bin/python
# filename: picktools.py
# codedtime:2015-3-25
import os
import 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、本文設計對中文字符的處理,所以使用正則表達式不太怎么方便,但不少不可以,后續版本中會添加對正則的支持!
3、由於初學中,所以代碼寫的不夠精煉簡潔,后續進行再優化!