Python的正则表达式,ascii转义字符到标签

时间:2016-12-14 14:42:52

标签: python regex python-2.7 ascii

我有以下Xterm的输出:

text = '\x1b[0m\x1b[01;32mattr\x1b[0m\n\x1b[01;36mawk\x1b[0m\n\x1b[01;32mbasename\x1b[0m\n\x1b[01;32mbash\n\x1b[0many text'

我知道\x1b[0m将删除所有文字属性,\x1b[01如果是粗体文字,\x1b[32m是绿色文字,\x1b[01;32m是粗体绿色文字。那么如何将这些转义字符传递给我自己的标签呢?像这样:

\x1b[0m\x1b[01;32mattr --> <bold><green>attr</bold></green>

我希望我的text变量成为:

text = '<bold><green>attr</bold></green>\n<bold><cyan>awk</bold></cyan>\n<bold><green>basename</bold></green>\n<bold><green>bash</bold></green>\nanytext'

1 个答案:

答案 0 :(得分:1)

import re

text = '\x1b[0m\x1b[01;32mattr\x1b[0m\n\x1b[01;36mawk\x1b[0m\n\x1b[01;32mbasename\x1b[0m\n\x1b[01;32mbash\n\x1b[0many text'

# dictionary mapping text attributes to tag names
fmt = {'01':'bold', '32m':'green', '36m': 'cyan'}
# regex that gets all text attributes, the text and any potential newline
groups = re.findall('(\n?)\\x1b\[((?:(?:0m|32m|01|36m);?)+)([a-zA-Z ]+)', text)
# iterate through the groups and build your new string
xml = []
for group in groups:
    g_text = group[2] # the text itself
    for tag in group[1].split(';'): # the text attributes 
        if tag in fmt:
            tag = fmt[tag]
        else:
            continue
        g_text = '<%s>%s</%s>' %(tag,g_text,tag)
    g_text = group[0] + g_text # add a newline if necessary
    xml.append(g_text)
xml_text = ''.join(xml)

print(xml_text)

<green><bold>attr</bold></green>
<cyan><bold>awk</bold></cyan>
<green><bold>basename</bold></green>
<green><bold>bash</bold></green>
any text

有关正则表达式的演示,请参阅此链接:Debuggex Demo

目前正则表达式假定您在实际文本中只有字母字符或空格,但可以在正则表达式的末尾更改此组([a-zA-Z ]+)以包含您在文本中可能包含的其他字符。

另外,我假设你有比粗体,绿色和青色更多的文字属性。您需要使用其他属性及其映射更新fmt字典。

编辑

@ Caaarlos&#39;如果ansi代码没有出现在fmt字典中,请在评论(如下)中将ansi代码保留为输出:

import re

text = '\x1b[0m\x1b[01;32;35mattr\x1b[0;7m\n\x1b[01;36mawk\x1b[0m\n\x1b[01;32;47mbasename\x1b[0m\n\x1b[01;32mbash\n\x1b[0many text'

fmt = {'01':'bold', '32':'green', '36': 'cyan'}

xml = []
active_tags = []
for group in re.split('\x1b\[', text):
    if group.strip():
        codes, text = re.split('((?:\d+;?)+)m', group)[1:]
        not_found = []
        for tag in codes.split(';'):
            if tag in fmt:
                tag = fmt[tag]
                text = '<%s>%s' %(tag,text)
                active_tags.append(tag)
            elif tag == '0':
                for a_tag in active_tags[::-1]:
                    text = '</%s>%s' %(a_tag,text)
                active_tags = []
            else:
                not_found.append(tag)
        if not_found:
            text = '\x1b[%sm%s' %(';'.join(not_found), text)
        xml.append(text)
xml_text = ''.join(xml)

print(repr(xml_text))

'\x1b[35m<green><bold>attr\x1b[7m</bold></green>\n<cyan><bold>awk</bold></cyan>\n\x1b[47m<green><bold>basename</bold></green>\n<green><bold>bash\n</bold></green>any text'

请注意,上面编辑过的代码还会处理标记在文本后不直接关闭的情况。