用python做工具_利用Python做工具-1

由於工作需要在一大堆日志里面提取相應的一些固定字符,如果單純靠手工取提取,數據量大,勞心勞力,於是自然而然想到了用Python做一個對應的提取工具,代替手工提取的繁雜,涉及中文字符,正則表達式不好匹配,但不是不可以實現,這個以后優化時再說。

需求描述:

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

需求解析:

首先獲取所有的Log日志的全路徑,根據路徑分別加載到將各個Log日志加載到內存中進行提取分析,並將結果存儲到給定的文本文件中。

解決方案:

為了盡可能的簡潔通用,這里使用配置文件作為輸入變量的依據。不多說,上代碼:

配置文件如下:

24cc6ee62d150d9f992088e7efd0330e.jpe

103文件夾下有兩個文件:log1.txt和log2.txt, 內容類似如下:

4cdc4ebaf57103c05735ab910c8d1822.jpe    

4e0b8d9accf36fdabc14b8c39810bec1.jpe

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

7558690247fc20f04ea6780809acccbc.jpe  

c95a31177143a42ce5bbddde33ae984b.jpe

心得體會:

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

2、本文設計對中文字符的處理,所以使用正則表達式不太怎么方便,但不少不可以,后續版本中會添加對正則的支持!

3、由於初學中,所以代碼寫的不夠精煉簡潔,后續進行再優化!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值