Python: Converting ANSI color codes to HTML -
i have program reads minecraft console output, , puts in qt text edit field (irrelevant). however, minecraft consoles use ansi color codes ([0;32;1m
) output colors, , i'd them in html format (since qt text edit fields read that).
i've researched bit , found bunch of solutions require style sheets, not want. want simple <span style="color: green"></span>
or similar, inline.
can 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'] none: if argsdict['arg_2'] 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>
Comments
Post a Comment