python提取檔案中的關鍵詞及部分上下文內容
阿新 • • 發佈:2019-01-22
也包含了資料夾中檔案遍歷
# -*- coding: utf-8 -*-
#允許中文註釋
#需要提取文字夾下所有文字的一些資訊(***有些需要轉換格式****),存到一個新檔案res.txt中
import re #正則模組
import os #檔案處理模組
import string #字串
fres = open('C:/Users/Administrator/Desktop/res.txt', 'w')
rootdir = 'C:/Users/Administrator/Desktop/log'
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
#print filename
fres.write(filename+'\n') #記錄下檔名,便於程式碼糾錯
# 提取hostname/sysname
f = open('C:/Users/Administrator/Desktop/log/'+str(filename))
lines = f.readlines() # .readlines() 自動將檔案內容分析成一個行的列表,加快編譯速度
for line in lines:
pattern = re.compile('(hostname|sysname).*' ) # s:space;()分組
match = pattern.match(line)
if match:
# 使用Match獲得分組資訊
fres.write(match.group() + '\n') # Ctrl /可以註釋多行
f.close()
# 提取uptime,將格式轉換為days
f1 = open('C:/Users/Administrator/Desktop/log/'+str(filename)) # 重新開啟,不然無法成功寫入
lines = f1.read()
t = re.findall('uptime.+', lines) # findall進行正則匹配,不知為何compile不行了o.o
# .:非換行任意字元,+:1次或任意次數;*:前一個字元0次或任意次
t_convert = ''.join(t) # list轉string
list = t_convert.split(' ') # 根據空格切片
y=0
w=0
d=0
if ('year,' in list): # 提取年、周...轉換型別計算
y = list[list.index('year,') - 1]
if ('years,' in list):
y = list[list.index('years,') - 1]
if ('weeks,' in list):
w = list[list.index('weeks,') - 1]
if ('days,' in list):
d = list[list.index('days,') - 1]
y = int(y)
w = int(w)
d = int(d)
days = 365 * y + 7 * w + d
fres.write('days: ' + str(days) + '\n') # 需進行型別轉換
f1.close()
# loopback要提取的地址在下一行
f2 = open('C:/Users/Administrator/Desktop/log/'+str(filename))
lines = f2.read()
t = re.findall('interface Loopback.+\n ip address \S*', lines)
t_convert = ''.join(t)
list = t_convert.split(' ')
fres.write('loopback: ' + list[-1] + '\n\n')
f2.close()
fres.close()