Python.search_wrk
Posted Breathing...
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python.search_wrk相关的知识,希望对你有一定的参考价值。
import stat
import tkinter
from tkinter.filedialog import *
def traversal_dir(dir_name): # 遍历目标路径下所有
rets = []
try:
if len(dir_name):
for r, ds, fs in os.walk(dir_name):
for i in ds:
rets.append(str(os.path.join(r, i)).replace('\', '/'))
for i in fs:
rets.append(str(os.path.join(r, i)).replace('\', '/'))
except Exception as e:
print(e)
return rets
class WrkWin(tkinter.Tk):
def __init__(self):
super().__init__()
self.entry_dir = tkinter.StringVar() # 目标路径控件
self.entry_dir.set('C:/Using/UnzipTool/WRK-v1.2')
self.entry_keystr = tkinter.StringVar() # 查找关键字
self.show()
def show(self):
self.title('search wrk-v1.2(.h)') # 窗口标题,可选
self.geometry('1000x300+200+100') # 窗口大小,宽x高+距左+距上,可选
self.resizable(width=False, height=False) # 窗口大小可否变化,可选
x0 = 10 # 布局起始x
y0 = 5 # 布局起始y
x_spacing = 80 # 行间距
y_spacing = 10 # 列间距
width = 10 # 控件宽度
height = 30 # 控件高度
line = 0 # 布局行号
pass # line0 选择目标路径
control = tkinter.Button(self, text='选择目标路径', width=width, command=self.select_dir)
control.place(x=x0, y=y0 + y_spacing * line + height * line)
control = tkinter.Entry(self, textvariable=self.entry_dir, width=100)
control.place(x=x0 + x_spacing * 1 + width * 1, y=y0 + y_spacing * line + height * line + 5)
pass # 查找关键字
line = 1
control = tkinter.Label(self, text='搜索关键字', width=width)
control.place(x=x0, y=y0 + y_spacing * line + height * line)
control = tkinter.Entry(self, textvariable=self.entry_keystr, width=100)
control.place(x=x0 + x_spacing * 1 + width * 1, y=y0 + y_spacing * line + height * line)
pass # 搜索
line = 2
control = tkinter.Button(self, text='搜索', width=width, command=self.search)
control.place(x=x0, y=y0 + y_spacing * line + height * line)
def select_dir(self):
try:
path = askdirectory()
if len(path):
self.entry_dir.set(path)
else:
self.entry_dir.set('')
except Exception as e:
print(e)
def search(self):
try:
path = self.entry_dir.get()
paths = traversal_dir(path)
hs = []
for i in paths:
if '.h'.upper() in i.upper():
hs.append(i)
keys = self.entry_keystr.get().split(' ')
rets = [] # [(行号, 文件全路径),...]
match = False;
for file in hs:
with open(file, 'r', encoding='utf8') as f:
lines = f.readlines()
for index in range(len(lines)):
for key in keys:
if key.upper() in lines[index].upper():
match = True
else:
match = False
break
if match:
rets.append((index, file))
with open('temp.txt', 'w', encoding='utf8') as f:
for item in rets:
f.write(str(item[0]) + ' ' + str(item[1]) + '
')
os.system('temp.txt')
os.chmod('temp.txt', stat.S_IWRITE)
os.remove('temp.txt')
except Exception as e:
print(e)
if __name__ == '__main__':
WrkWin().mainloop()
以上是关于Python.search_wrk的主要内容,如果未能解决你的问题,请参考以下文章