Python 正则表达式
Python 字符串处理
曾经自己的写的 GUI
一个坑
没有料到用 vars()
的时候发现了一个诡异的坑,我只是想输出的时候偷懒一下,于是乎,这玩意儿的输出顺序简直逆天了!!!回头补坑吧,暂时找不到什么好方法。
附代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import tkFileDialog, Tkinter, tkMessageBox
# csv 文件表头
excelHeader = ['fromZone', 'toZone', 'policyName', 'sourceAddress', 'destinationAddress', 'application', 'permit', 'log']
# re 编译 string
reWord_source = r'set security policies from-zone (\S+) to-zone (\S+) policy (\S+) match source-address (\S+)'
reWord_destination = r'set security policies from-zone (\S+) to-zone (\S+) policy (\S+) match destination-address (\S+)'
reWord_application = r'set security policies from-zone (\S+) to-zone (\S+) policy (\S+) match application (\S+)'
reWord_permit = r'set security policies from-zone (\S+) to-zone (\S+) policy (\S+) then permit([^(\n|\r)]*)'
reWord_log = r'set security policies from-zone (\S+) to-zone (\S+) policy (\S+) then log([^(\n|\r)]*)'
# 正则表达式编译成 Pattern 对象
pattern_source = re.compile(reWord_source)
pattern_destination = re.compile(reWord_destination)
pattern_application = re.compile(reWord_application)
pattern_permit = re.compile(reWord_permit)
pattern_log = re.compile(reWord_log)
# print the obj
def printObj(obj):
print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])
# 连接列表成字符串
def joinListElementToStrWithSymbol(listObj, symbol):
return '"' + symbol.join(listObj) + '"'
# 去除 '\uxxx'
def escapeUnicode(obj):
strObj = '' + obj
return strObj.encode('utf8')
# 连接元组成字符串
def joinTupleElementToStrWithSymbol(tupleObj, symbol):
return '"' + symbol.join(tupleObj) + '"'
# 正则匹配
def matchContentWithPattern(content, pattern):
match = pattern.match(content)
return match
# 写 csv 表头
def writeHeader(fileObj):
for value in excelHeader:
fileObj.write(value + ",")
fileObj.write('\n')
# 感谢我曾经封装过这么草率的 gui(主要是因为==忘记怎么写 Tk 了)
def gui():
# 文件目录
def filedir():
filedire = tkFileDialog.askdirectory()
filetemp = textfile.get()
filetemp = filetemp.split(filedire)[1].split('.txt')[0]
if filedire == '':
textdir.set('')
else:
textdir.set(filedire + filetemp + '.csv')
# Config文件
def filenam():
filename = tkFileDialog.askopenfilename()
if filename == '':
textfile.set('')
else:
textfile.set(filename)
# 信息确认
def panduan():
if textdir.get() == '':
tkMessageBox.showinfo("Info", "文件目录不能为空")
return
elif textfile.get() == '':
tkMessageBox.showinfo("Info", "Config文件不能为空")
return
else:
test.destroy()
# 主窗口
test = Tkinter.Tk()
test.geometry('400x180')
test.title('txt 转换配置')
# host信息录入系统
label = Tkinter.Label(test, text = "Input 文件:")
label.pack()
textfile = Tkinter.StringVar()
textfile.set("")
entryfile = Tkinter.Entry(test, textvariable = textfile)
entryfile.pack()
buttonfile = Tkinter.Button(test, text = "选择 Config 文件", command = filenam)
buttonfile.pack()
# 日常config保存路径
label = Tkinter.Label(test, text = "Output 文件:")
label.pack()
textdir = Tkinter.StringVar()
textdir.set("{Current Directory}/output.csv")
entrydir = Tkinter.Entry(test, textvariable = textdir)
entrydir.pack()
buttondir = Tkinter.Button(test, text = "打开文件目录", command = filedir)
buttondir.pack()
# 检查确认录入信息
Confirmbutton = Tkinter.Button(test, text = "确认", command = panduan)
Confirmbutton.pack()
test.mainloop()
return (test, textdir.get(), textfile.get())
# 解决输出顺序的问题
# class Base:
# def __init__(self, fromZone, toZone, policyName):
# self.fromZone = fromZone
# self.toZone = toZone
# self.policyName = policyName
class Entry:
def __init__(self, fromZone, toZone, policyName):
self.fromZone = fromZone
self.toZone = toZone
self.policyName = policyName
self.sourceAddress = []
self.destinationAddress = []
self.application = []
self.permit = []
self.log = []
# 判断是否为正在处理的对象
def ifTheSameObjAsPrevious(self, fromZone, toZone, policyName):
if fromZone == self.fromZone and toZone == self.toZone and policyName == self.policyName:
return True
return False
# 写入 csv
def writeObjToCsv(self, fileObj):
fileObj.write(escapeUnicode(self.fromZone) + ',')
fileObj.write(escapeUnicode(self.toZone) + ',')
fileObj.write(escapeUnicode(self.policyName) + ',')
self.sourceAddress = joinListElementToStrWithSymbol(self.sourceAddress, '\n')
self.destinationAddress = joinListElementToStrWithSymbol(self.destinationAddress, '\n')
self.application = joinListElementToStrWithSymbol(self.application, '\n')
self.permit = joinListElementToStrWithSymbol(self.permit, '\n')
self.log = joinListElementToStrWithSymbol(self.log, '\n')
fileObj.write(escapeUnicode(self.sourceAddress) + ',')
fileObj.write(escapeUnicode(self.destinationAddress) + ',')
fileObj.write(escapeUnicode(self.application) + ',')
fileObj.write(escapeUnicode(self.permit) + ',')
fileObj.write(escapeUnicode(self.log) + ',')
fileObj.write('\n')
if ( __name__ == "__main__"):
tkHandler, writeFileName, readFileName = gui()
# 读写文件句柄创建
fp_r = open(readFileName, 'r')
fp_w = open(writeFileName, 'w')
writeHeader(fp_w)
# 放置处理对象
entryObj = ""
# 处理输入流
content = fp_r.readline()
while content:
# 源
match = matchContentWithPattern(content, pattern_source)
if match:
fromZone, toZone, policyName, sourceAddress = match.groups()
# 是初始化状态新建 obj,和append;不是之前正在处理的对象,保存之前的entryObj,并新建obj,和append;是之前正在处理的对象,append
if entryObj == "":
entryObj = Entry(fromZone, toZone, policyName)
elif not entryObj.ifTheSameObjAsPrevious(fromZone, toZone, policyName):
# printObj(entryObj)
entryObj.writeObjToCsv(fp_w)
entryObj = Entry(fromZone, toZone, policyName)
entryObj.sourceAddress.append(sourceAddress)
# 目的
match = matchContentWithPattern(content, pattern_destination)
if match:
fromZone, toZone, policyName, destinationAddress = match.groups()
entryObj.destinationAddress.append(destinationAddress)
# app
match = matchContentWithPattern(content, pattern_application)
if match:
fromZone, toZone, policyName, application = match.groups()
entryObj.application.append(application)
# permit
match = matchContentWithPattern(content, pattern_permit)
if match:
fromZone, toZone, policyName, permit = match.groups()
entryObj.permit.append("permit" + permit)
# log
match = matchContentWithPattern(content, pattern_log)
if match:
fromZone, toZone, policyName, log = match.groups()
entryObj.log.append("log" + log)
content = fp_r.readline()
else:
# 保存最后一个对象
entryObj.writeObjToCsv(fp_w)
# 关闭文件句柄
fp_r.close()
fp_w.close()
# 关闭 gui 句柄
# tkHandler.destroy()
print "Success!"