首頁 > 軟體

Python利用pangu模組實現文字格式化小工具

2022-10-10 14:01:11

其實使用pangu做文字格式標準化的業務程式碼在之前就實現了,主要能夠將中文文字檔案中的文字、標點符號等進行標準化。

但是為了方便起來我們這裡使用了Qt5將其做成了一個可以操作的頁面應用,這樣不熟悉python的朋友就可以不用寫程式碼直接雙擊執行使用就OK了。

為了使文字格式的美化過程不影響主執行緒的使用,特地採用QThread子執行緒來專門的執行文字檔案美化的業務過程,接下來還是採用pip的方式將所有需要的非標準模組安裝一下。

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pangu

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyQt5

將我們使用到的pyqt5應用製作模組以及業務模組pangu匯入到我們的程式碼塊中。

# It imports all the classes, attributes, and methods of the PyQt5.QtCore module into the global symbol table.
from PyQt5.QtCore import *

# It imports all the classes, attributes, and methods of the PyQt5.QtWidgets module into the global symbol table.
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QTextBrowser, QLineEdit, QPushButton, 
    QFormLayout, QFileDialog

# It imports all the classes, attributes, and methods of the PyQt5.QtGui module into the global symbol table.
from PyQt5.QtGui import QIcon, QFont, QTextCursor

# It imports the pangu module.
import pangu

# It imports the sys module.
import sys

# It imports the os module.
import os

為了減少python模組在打包時資源佔用過多,打的exe應用程式的佔用空間過大的情況,這次我們只匯入了能夠使用到的相關python類,這個小細節大家注意一下。

下面建立一個名稱為PanGuUI的python類來實現對整個應用頁面的開發,將頁面的佈局以及元件相關的部分寫到這個類中。並且給頁面元件繫結好相應的槽函數從而實現頁面的'點選'等功能。

# It creates a class called PanGuUI that inherits from QWidget.
class PanGuUI(QWidget):
    def __init__(self):
        """
        A constructor. It is called when an object is created from a class and it allows the class to initialize the
        attributes of a class.
        """
        super(PanGuUI, self).__init__()
        self.init_ui()

    def init_ui(self):
        """
        This function initializes the UI.
        """
        self.setWindowTitle('文字檔案美化器 公眾號:Python 集中營')
        self.setWindowIcon(QIcon('txt.ico'))

        self.brower = QTextBrowser()
        self.brower.setFont(QFont('宋體', 8))
        self.brower.setReadOnly(True)
        self.brower.setPlaceholderText('處理程序展示區域...')
        self.brower.ensureCursorVisible()

        self.txt_file_path = QLineEdit()
        self.txt_file_path.setPlaceholderText('源文字檔案路徑')
        self.txt_file_path.setReadOnly(True)

        self.txt_file_path_btn = QPushButton()
        self.txt_file_path_btn.setText('匯入')
        self.txt_file_path_btn.clicked.connect(self.txt_file_path_btn_click)

        self.new_txt_file_path = QLineEdit()
        self.new_txt_file_path.setPlaceholderText('新文字檔案路徑')
        self.new_txt_file_path.setReadOnly(True)

        self.new_txt_file_path_btn = QPushButton()
        self.new_txt_file_path_btn.setText('路徑')
        self.new_txt_file_path_btn.clicked.connect(self.new_txt_file_path_btn_click)

        self.start_btn = QPushButton()
        self.start_btn.setText('開始匯入')
        self.start_btn.clicked.connect(self.start_btn_click)

        hbox = QHBoxLayout()
        hbox.addWidget(self.brower)

        fbox = QFormLayout()
        fbox.addRow(self.txt_file_path, self.txt_file_path_btn)
        fbox.addRow(self.new_txt_file_path, self.new_txt_file_path_btn)

        v_vbox = QVBoxLayout()
        v_vbox.addWidget(self.start_btn)

        vbox = QVBoxLayout()
        vbox.addLayout(fbox)
        vbox.addLayout(v_vbox)

        hbox.addLayout(vbox)

        self.thread_ = PanGuThread(self)
        self.thread_.message.connect(self.show_message)
        self.thread_.finished.connect(self.finshed)

        self.setLayout(hbox)

    def show_message(self, text):
        """
        It shows a message

        :param text: The text to be displayed
        """
        cursor = self.brower.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.brower.append(text)
        self.brower.setTextCursor(cursor)
        self.brower.ensureCursorVisible()

    def txt_file_path_btn_click(self):
        """
        It opens a file dialog box and allows the user to select a file.
        """
        txt_file = QFileDialog.getOpenFileName(self, os.getcwd(), '開啟文字檔案',
                                               'Text File(*.txt)')
        self.txt_file_path.setText(txt_file[0])

    def new_txt_file_path_btn_click(self):
        """
        This function opens a file dialog box and allows the user to select a file to save the output to.
        """
        new_txt_file = QFileDialog.getOpenFileName(self, os.getcwd(), '開啟文字檔案',
                                                   'Text File(*.txt)')
        self.new_txt_file_path.setText(new_txt_file[0])

    def start_btn_click(self):
        """
        A function that is called when the start button is clicked.
        """
        self.thread_.start()
        self.start_btn.setEnabled(False)

    def finshed(self, finished):
        """
        :param finished: A boolean value that is True if the download is finished, False otherwise
        """
        if finished is True:
            self.start_btn.setEnabled(True)

建立名稱為PanGuThread的子執行緒,將具體實現美化格式化文字字串的業務程式碼塊寫入到子執行緒中。子執行緒繼承的是QThread的PyQt5的執行緒類,通過建立子執行緒並且將子執行緒的訊號資訊傳遞到主執行緒中,在主執行緒的文字瀏覽器中進行展示達到實時跟蹤執行結果的效果。

# This class is a subclass of QThread, and it's used to split the text into words
class PanGuThread(QThread):
    message = pyqtSignal(str)
    finished = pyqtSignal(bool)

    def __init__(self, parent=None):
        """
        A constructor that initializes the class.

        :param parent: The parent widget
        """
        super(PanGuThread, self).__init__(parent)
        self.working = True
        self.parent = parent

    def __del__(self):
        """
        A destructor. It is called when the object is destroyed.
        """
        self.working = True
        self.wait()

    def run(self) -> None:
        """
        > This function runs the program
        """
        try:

            txt_file_path = self.parent.txt_file_path.text().strip()
            self.message.emit('原始檔路徑資訊讀取正常!')
            new_txt_file_path = self.parent.new_txt_file_path.text().strip()
            self.message.emit('新檔案路徑資訊讀取正常!')
            list_ = []
            with open(txt_file_path, encoding='utf-8') as f:
                lines_ = f.readlines()
                self.message.emit('原始檔內容讀取完成!')
                n = 1
                for line_ in lines_:
                    text = pangu.spacing_text(line_)
                    self.message.emit('第{0}行檔案內容格式化完成!'.format(n))
                    list_.append(text)
                    n = n + 1
                self.message.emit('原始檔路徑資訊格式化完成!')

            self.message.emit('即將開始將格式化內容寫入新檔案!')
            with open(new_txt_file_path, 'a') as f:
                for line_ in list_:
                    f.write(line_ + 'n')
            self.message.emit('新檔案內容寫入完成!')
            self.finished.emit(True)

        except Exception as e:
            self.message.emit('檔案內容讀取或格式化發生異常!')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = PanGuUI()
    main.show()
    sys.exit(app.exec_())

完成了開發開始測試一下效果如何,建立了兩個文字檔案data.txt、new_data.txt,點選'開始執行'之後會調起整個的業務子執行緒實現文字格式化,結果完美執行來看一下執行過程展示。

到此這篇關於Python利用pangu模組實現文字格式化小工具的文章就介紹到這了,更多相關Python pangu文字格式化內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com