简体   繁体   中英

Python: Converting ANSI color codes to HTML

I have a program that reads Minecraft console output, and puts it in a Qt text edit field (irrelevant). However, Minecraft consoles use ANSI color codes ( [0;32;1m ) to output colors, and I'd like them in HTML format (since Qt text edit fields read that).

I've researched a bit and found a bunch of solutions that require style sheets, which is not what I want. What I want is a simple <span style="color: green"></span> or similar, inline.

Can anyone help me achieve this?

import re

COLOR_DICT = {
    '31': [(255, 0, 0), (128, 0, 0)],
    '32': [(0, 255, 0), (0, 128, 0)],
    '33': [(255, 255, 0), (128, 128, 0)],
    '34': [(0, 0, 255), (0, 0, 128)],
    '35': [(255, 0, 255), (128, 0, 128)],
    '36': [(0, 255, 255), (0, 128, 128)],
}

COLOR_REGEX = re.compile(r'\[(?P<arg_1>\d+)(;(?P<arg_2>\d+)(;(?P<arg_3>\d+))?)?m')

BOLD_TEMPLATE = '<span style="color: rgb{}; font-weight: bolder">'
LIGHT_TEMPLATE = '<span style="color: rgb{}">'


def ansi_to_html(text):
    text = text.replace('[m', '</span>')

    def single_sub(match):
        argsdict = match.groupdict()
        if argsdict['arg_3'] is None:
            if argsdict['arg_2'] is None:
                color, bold = argsdict['arg_1'], 0
            else:
                color, bold = argsdict['arg_1'], int(argsdict['arg_2'])
        else:
            color, bold = argsdict['arg_2'], int(argsdict['arg_3'])

        if bold:
            return BOLD_TEMPLATE.format(COLOR_DICT[color][1])
        return LIGHT_TEMPLATE.format(COLOR_DICT[color][0])

    return COLOR_REGEX.sub(single_sub, text)

print ansi_to_html('[06-10-13 21:28:23] [INFO] [0;31;1mUsage: /kick [reason ...][m')
print ansi_to_html('[06-10-13 21:28:23] [INFO] [31;0mUsage: /kick [reason ...][m')
print ansi_to_html('[06-10-13 21:28:23] [INFO] [31mUsage: /kick [reason ...][m')

[06-10-13 21:28:23] [INFO] <span style="color: rgb(128, 0, 0); font-weight: bolder">Usage: /kick [reason ...]</span>
[06-10-13 21:28:23] [INFO] <span style="color: rgb(255, 0, 0)">Usage: /kick [reason ...]</span>
[06-10-13 21:28:23] [INFO] <span style="color: rgb(255, 0, 0)">Usage: /kick [reason ...]</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM