信息搜索软件,查找范围为doc、docx、xls、xlsx、txt文件,python+Qt实现

#main.py
from PyQt5.QtWidgets import QApplication, QLabel
from queryWindow import  Query_Window

if __name__ == "__main__":
    app = QApplication([])
    label = Query_Window()
    label.show()
    app.exec_()

#UI文件 Ui_MainWindow.py
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setMinimumSize(QtCore.QSize(0, 50))
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")
        self.verticalLayout_2.addWidget(self.label_3)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.path = QtWidgets.QLineEdit(self.centralwidget)
        self.path.setObjectName("path")
        self.horizontalLayout.addWidget(self.path)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.data = QtWidgets.QLineEdit(self.centralwidget)
        self.data.setObjectName("data")
        self.horizontalLayout.addWidget(self.data)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.fileList = QtWidgets.QListView(self.centralwidget)
        self.fileList.setObjectName("fileList")
        self.verticalLayout.addWidget(self.fileList)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_2.setText(_translate("MainWindow", "路径:"))
        self.label.setText(_translate("MainWindow", "查找内容:"))
        self.pushButton.setText(_translate("MainWindow", "查找"))

#主窗口类 query_Window.py
from  Ui_MainWindow import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from qurey_thread import Query_Thread


class Query_Window(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.query_start)
        self.model = QtCore.QStringListModel()
        self.ansList = QtCore.QStringListModel().stringList()
        self.model.setStringList(self.ansList)
        self.ui.fileList.setModel(self.model)
        self.ui.fileList.setEditTriggers(QtWidgets.QListView.NoEditTriggers)
        self.ui.fileList.doubleClicked.connect(self.open_file)
        self.query_thread = Query_Thread(w=self)
        self.query_thread.start()


    def open_file(self, index):
        file = self.model.data(index, 0)
        print(file)
        try:
            QtGui.QDesktopServices.openUrl(QtCore.QUrl("file:" + file, QtCore.QUrl.TolerantMode))
        except Exception as e:
            print(str(e))

    def query_start(self):
        self.query()

    def query(self):
        self.query_thread.start_query(self.ui.path.text(), self.ui.data.text())

    def insert_data(self, file):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row)
        self.model.setData(index, file)

#查找的线程类(目前只有一个后台线程,如果哪位同学有兴趣,可以设计成线程池,那样更快一些)
#query_thread.py

import threading
import queryWindow
from PyQt5 import QtCore
import xlrd
import docx
import os
import win32com.client as wc


class Query_Thread(threading.Thread):
    def __init__(self, w: queryWindow):
        threading.Thread.__init__(self)
        self.data = str()
        self.path = str()
        self.mainWindow = w
        self.abort = True
        self.word = wc.Dispatch("Word.Application")
        self.Semaphore = threading.Semaphore(value=0)
        self.stopSemaphore = threading.Semaphore(value=1)

    def __del__(self):
        self.word.Quit()

    def run(self):
        while True:
            self.Semaphore.acquire()
            try:
                path = self.path
                data = self.data
                if path[len(path) - 1] == '\\' or path[len(path) - 1] == '/':
                    path = path[0:len(path)-1]
                if len(data) == 0:
                    return
                typeList = QtCore.QStringListModel().stringList()
                typeList.append("*.xls")
                typeList.append("*.doc")
                typeList.append("*.xlsx")
                typeList.append("*.docx")
                typeList.append("*.txt")
                dirList = QtCore.QStringListModel().stringList()
                dirList.append(path)
                while len(dirList) > 0:
                    if self.abort:
                        break
                    dire = QtCore.QDir(dirList[0])
                    del dirList[0]
                    if not dire.exists():
                        continue
                    files = dire.entryList(typeList, dire.Files | dire.Readable | dire.Name)
                    for file in files:
                        try:
                            file = dire.path() + '/' + file
                            print(file)
                            hasFound = False
                            if file.find(data) != -1:
                                self.mainWindow.insert_data(file)
                                hasFound = True
                                continue
                            if QtCore.QFileInfo(file).suffix() == "docx":
                                fileData = docx.Document(file)
                                for line in fileData.paragraphs:
                                    if line.text.find(data) != -1:
                                        self.mainWindow.insert_data(file)
                                        hasFound = True
                                        break
                            elif QtCore.QFileInfo(file).suffix() == "doc":
                                docxFile = str()
                                doc = self.word.Documents.Open(file)
                                docxFile = dire.path() + '/' + QtCore.QFileInfo(file).completeBaseName() + ".tmp.docx"
                                doc.SaveAs(docxFile, 12, False, "", True, "", False, False, False, False)
                                doc.Close()
                                fileData = docx.Document(docxFile)
                                for line in fileData.paragraphs:
                                    if line.text.find(data) != -1:
                                        self.mainWindow.insert_data(file)
                                        hasFound = True
                                        break
                                os.remove(docxFile)
                            elif QtCore.QFileInfo(file).suffix() == "xls" or QtCore.QFileInfo(file).suffix() == "xlsx":
                                try:
                                    xlsData = xlrd.open_workbook(file)
                                    indexNum = len(xlsData.sheets())
                                    for i in range(indexNum):
                                        table = xlsData.sheets()[i]
                                        nrows = table.nrows  # 行数
                                        ncols = table.ncols  # 列数
                                        for rownum in range(nrows):
                                            row = table.row_values(rownum)
                                            if row:
                                                for j in range(ncols):
                                                    if str(row[j]).find(data) != -1:
                                                        self.mainWindow.insert_data(file)
                                                        hasFound = True
                                                        break
                                            if hasFound:
                                                break
                                        if hasFound:
                                            break
                                except Exception as e:
                                    print(str(e))

                            elif QtCore.QFileInfo(file).suffix() == "txt":
                                fileData = str()
                                try:
                                    fileData = open(file, 'r').read()
                                    if fileData.find(data) != -1:
                                        self.mainWindow.insert_data(file)
                                        hasFound = True
                                        break
                                except Exception as e:
                                    print(str(e))
                        except Exception as e:
                            print(str(e))
                    dires = dire.entryList(dire.Dirs)
                    if len(dires) > 0:
                        while len(dires) > 0 and (dires[0] == '.' or dires[0] == '..'):
                            del dires[0]
                        dirList += [dire.path() + "/" + x for x in dires]
            except Exception as e:
                print(str(e))
            self.stopSemaphore.release()

    def start_query(self, path: str, data: str):
        self.path = path.strip()
        self.data = data.strip()
        self.abort = True
        self.stopSemaphore.acquire()
        cou = self.mainWindow.model.rowCount()
        self.mainWindow.model.removeRows(0, cou)
        self.abort = False
        self.Semaphore.release()






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值