如何在python中更改指定单词的颜色

时间:2018-04-10 09:43:40

标签: python html regex file

如何使用python更改文本文件中所选单词的颜色?

以下函数从文件中读取并匹配请求的单词,如果它发现它将表达式的颜色更改为红色。

问题在于,当我运行程序时,HTML标记在textBox中显示为文本,而不是像这样的颜色。

 "<b><span style='color:white;mso-themecolor:background1;background:black;mso-highlight:black'>"+searchedSTR+"

&#34; 我将非常感谢您对此问题的任何帮助

的代码:

def readFile(self, currentFile):

        self.textEdit_PDFpreview.clear()        
        searchedSTR = self.lineEditSearch.text()
        try:
            with open(currentFile) as ctf:
                ctfRead = ctf.read()               
                fileName = os.path.basename(currentFile)        
                RepX = "<b><span style='color:white;mso-themecolor:background1;background:black;mso-highlight:black'>"+st+"</span></b>"

                thematch=re.sub(searchedSTR,RepX,ctfRead)
                print("the match \n{}".format(thematch))
                matches = re.findall(searchedSTR, ctfRead, re.MULTILINE | re.IGNORECASE)                    
                print(" matches is: \n{}".format(matches))

                if matches:  
                    self.textEdit_PDFpreview.insertHtml(thematch)
                else:
                    print("Not Found")
                    self.textEdit_PDFpreview.insertHtml(str("no match found"))

功能代码:

import  mainwindow

from PyQt5 import QtCore, QtGui, QtWidgets


class appwindow(mainwindow.Ui_MainWindow):
        def __init__(self,winObj:QtWidgets.QMainWindow):
                self.winObj = winObj
                self.setupUi(winObj)
                self.winObj.show()
                self.pushButton.clicked.connect(self.changeColor)

        def changeColor(self):
                st ="test"
                x = "<b><span style='color:white;mso-themecolor:background1;background:black;mso-highlight:black'>"+st+"</span></b>"

                self.textEdit.insertHtml(x)


if __name__ == "__main__":

        import sys
        app = QtWidgets.QApplication(sys.argv)
        ImainWindow = QtWidgets.QMainWindow()
        ui = appwindow(ImainWindow)
        sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

我改变声明后的功能工作:

  self.textEdit_PDFpreview.insertHtml(thematch)

 self.textEdit_PDFpreview.setHtml(str(thematch))