Quantcast
Viewing all articles
Browse latest Browse all 14069

Python library that color text which is a code?

I am building Chat but not web based, Python based.in the chat you exchange information with the AI API.I was wondering if there is libary that recognize that this is code text and color it with the right colors, cause now I did some manual work and it looks bad.

class PythonHighlighter(QSyntaxHighlighter):def __init__(self, parent=None):    super().__init__(parent)    self._highlight_rules = []    # Keyword format    keyword_format = QTextCharFormat()    keyword_format.setForeground(QColor("blue"))    keyword_format.setFontWeight(QFont.Bold)    keywords = ["False", "await", "else", "import", "pass", "None", "break", "except", "in", "raise", "True", "class", "finally", "is", "return", "and", "continue", "for", "lambda", "try", "as", "def","from","nonlocal","while","assert","del","global","not","with","async","elif","if","or","yield","print","range","open","self"]    self._highlight_rules.append((QRegExp(r"\b" +"|".join(keywords) + r"\b"), keyword_format))    # String format    string_format = QTextCharFormat()    string_format.setForeground(QColor("green"))    self._highlight_rules.append((QRegExp(r"\".*\""), string_format))    self._highlight_rules.append((QRegExp(r"\'.*\'"), string_format))    # Comment format    comment_format = QTextCharFormat()    comment_format.setForeground(QColor("gray"))    self._highlight_rules.append((QRegExp(r"#[^\n]*"), comment_format))def highlightBlock(self, text):    for pattern, format in self._highlight_rules:        expression = QRegExp(pattern)        index = expression.indexIn(text)        while index >= 0:            length = expression.matchedLength()            self.setFormat(index, length, format)            index = expression.indexIn(text, index + length)

Viewing all articles
Browse latest Browse all 14069

Trending Articles