【问题标题】:String literal VT100 representation to unicode字符串文字 VT100 表示为 unicode
【发布时间】:2017-12-31 04:01:11
【问题描述】:

如何转换以下字符串文字:

token = "\x1b(0l\x1b(BHeader"

进入:

"┌Header"

我正在从库中接收文字 Unix 制图字符,需要转换为 unicode 以进行单元测试。

【问题讨论】:

  • 我从未听说过“文字 Unix 方框绘图字符”。你有关于这是什么的参考吗?在您显示的字符串中,我看到了 ESC 控制字符 (U+1B) 和一些常见的 ASCII 字符((01B)。

标签: python python-3.x unicode


【解决方案1】:

这是 VT-100 替代字符集(在编辑问题主题之前不太明显)。序列esc ( 0 将编码更改为备用集,序列esc ( B 将其改回。只有少数这样的字符被映射。这是映射。

    0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
6                                           ┘   ┐   ┌   └   ┼   
7       ─           ├   ┤   ┴   ┬   │                           

要进行转换,您必须设置一个 dict 将这些代码映射到相应的 Unicode 代码点并自行转换。

【讨论】:

    【解决方案2】:

    @BoarGules 是正确的。这是我对这样的字符串进行解码的解决方案:

    vt_100_mapping = {
        '0x71': '─',
        '0x74': '├',
        '0x75': '┤',
        '0x76': '┴',
        '0x77': '┬',
        '0x78': '│',
        '0x6a': '┘',
        '0x6b': '┐',
        '0x6c': '┌',
        '0x6d': '└',
        '0x6e': '┼',
    }
    

    from itertools import groupby
    
    def decode_vt_100(iterable, default_set='(B', alt_set='(0'):
        for is_escape, group in groupby(iterable, lambda _: _ =='\x1b'):
            if is_escape:
                continue
    
            characters = ''.join(group)
    
            if characters.startswith(default_set):
                yield characters[len(default_set):]
    
            elif characters.startswith(alt_set):
                for character in characters[len(alt_set):]:
                    yield vt_100_mapping[hex(ord(character))]
    

    >>> print(''.join(decode_vt_100("\x1b(0l\x1b(BHeader")))
    ┌Header
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-23
      • 2018-07-23
      • 2011-03-09
      • 1970-01-01
      • 2017-11-05
      • 2020-06-23
      • 2013-06-21
      • 2011-11-30
      相关资源
      最近更新 更多