其实使用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,点击'开始运行'之后会调起整个的业务子线程实现文本格式化,结果完美运行来看一下执行过程展示。

【往期精彩】
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h