当前位置: 首页>>代码示例>>Python>>正文


Python wcwidth.wcswidth函数代码示例

本文整理汇总了Python中wcwidth.wcswidth函数的典型用法代码示例。如果您正苦于以下问题:Python wcswidth函数的具体用法?Python wcswidth怎么用?Python wcswidth使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了wcswidth函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: textwidth

 def textwidth(text):
     if isinstance(text, unicode):
         length = wcwidth.wcswidth(text)
         return len(text) if length == -1 else length
     else:
         text = text.decode("utf-8", "replace")
         length = wcwidth.wcswidth(text)
         return len(text) if length == -1 else length
开发者ID:ericpruitt,项目名称:swadr,代码行数:8,代码来源:swadr.py

示例2: _visible_width

def _visible_width(s):
    """Visible width of a printed string. ANSI color codes are removed.

    >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
    (5, 5)

    """
    if isinstance(s, _text_type) or isinstance(s, _binary_type):
        return wcswidth(_strip_invisible(s))
    else:
        return wcswidth(_text_type(s))
开发者ID:avdd,项目名称:pgcli,代码行数:11,代码来源:tabulate.py

示例3: force_text

 def force_text(self, text, prompt=False):
     if isinstance(text, str):
         text = text.decode('utf-8')
     if prompt:
         text_length = wcswidth(text + self.page_index)
         ret = text + (self.width - text_length) * u' ' + self.page_index
     else:
         text_length = wcswidth(text)
         ret = text + (self.width - text_length) * u' '
     # XXX stdout = unicode -> ansii NG(maybe ansii encode fail)
     # XXX stdout = unicode -> str OK
     return ret.encode('utf-8')
开发者ID:wanshot,项目名称:templa,代码行数:12,代码来源:model.py

示例4: _get_line_with_reprcrash_message

def _get_line_with_reprcrash_message(config, rep, termwidth):
    """Get summary line for a report, trying to add reprcrash message."""
    from wcwidth import wcswidth

    verbose_word = rep._get_verbose_word(config)
    pos = _get_pos(config, rep)

    line = "%s %s" % (verbose_word, pos)
    len_line = wcswidth(line)
    ellipsis, len_ellipsis = "...", 3
    if len_line > termwidth - len_ellipsis:
        # No space for an additional message.
        return line

    try:
        msg = rep.longrepr.reprcrash.message
    except AttributeError:
        pass
    else:
        # Only use the first line.
        i = msg.find("\n")
        if i != -1:
            msg = msg[:i]
        len_msg = wcswidth(msg)

        sep, len_sep = " - ", 3
        max_len_msg = termwidth - len_line - len_sep
        if max_len_msg >= len_ellipsis:
            if len_msg > max_len_msg:
                max_len_msg -= len_ellipsis
                msg = msg[:max_len_msg]
                while wcswidth(msg) > max_len_msg:
                    msg = msg[:-1]
                if six.PY2:
                    # on python 2 systems with narrow unicode compilation, trying to
                    # get a single character out of a multi-byte unicode character such as
                    # u'😄' will result in a High Surrogate (U+D83D) character, which is
                    # rendered as u'�'; in this case we just strip that character out as it
                    # serves no purpose being rendered
                    try:
                        surrogate = six.unichr(0xD83D)
                        msg = msg.rstrip(surrogate)
                    except ValueError:  # pragma: no cover
                        # Jython cannot represent this lone surrogate at all (#5256):
                        # ValueError: unichr() arg is a lone surrogate in range
                        #     (0xD800, 0xDFFF) (Jython UTF-16 encoding)
                        # ignore this case as it shouldn't appear in the string anyway
                        pass
                msg += ellipsis
            line += sep + msg
    return line
开发者ID:lfernandez55,项目名称:flask_books,代码行数:51,代码来源:terminal.py

示例5: erase

    def erase(self, string, keypress=chr(127)):
        """ .. method:: erase(string, keypress=chr(127)) -> string

            Returns sequence for erasing ``string`` preceeding cursor given
            the erase character ``keypressed`` (one of chr(127) or 8) has
            been used to perform deletion, assisting predicted cursor
            movement of sessions using remote line editing with echo off.
        """
        assert keypress in (chr(127), chr(8)), chr
        string_disp = "".join(
            (
                (_char if self.stream.can_write(_char) and _char.isprintable() else name_unicode(_char))
                for _char in string
            )
        )
        vtlen = wcwidth.wcswidth(string_disp)
        assert vtlen >= 0, string

        # non-BSD clients will echo
        if self.stream.will_echo:
            return ("\b" * vtlen) + "\x1b[K"

        # BSD has strange behavior for line editing with local echo:
        if keypress == chr(127):
            # (1) '^?' actually advances the cursor right one cell,
            return "\b" + ("\b" * vtlen) + "\x1b[K"
        else:
            # (2) whereas '^h' moves the cursor left one (displayable) cell !
            return "\b" * (vtlen - 1) + "\x1b[K"
开发者ID:wjwwood,项目名称:telnetlib3,代码行数:29,代码来源:telsh.py

示例6: format_field

    def format_field(self, value, format_spec):
        if not isinstance(value, str):
            # If `value` is not a string use format built-in
            return format(value, format_spec)
        if format_spec == '':
            # If `format_spec` is empty we just return the `value` string
            return value

        print_length = wcwidth.wcswidth(value)
        if len(value) == print_length:
            return format(value, format_spec)

        fill, align, width, format_spec = UnicodeFormatter.parse_align(format_spec)
        if width == 0:
            return value
        formatted_value = format(value, format_spec)
        pad_len = width - print_length
        if pad_len <= 0:
            return formatted_value
        left_pad = ''
        right_pad = ''
        if align in '<=':
            right_pad = fill * pad_len
        elif align == '>':
            left_pad = fill * pad_len
        elif align == '^':
            left_pad = fill * math.floor(pad_len/2)
            right_pad = fill * math.ceil(pad_len/2)
        return ''.join((left_pad, formatted_value, right_pad))
开发者ID:raphaelahrens,项目名称:doto,代码行数:29,代码来源:printing.py

示例7: monospaced_width

def monospaced_width(text):
    r"""
    Return the number of character cells that this string is likely to occupy
    when displayed in a monospaced, modern, Unicode-aware terminal emulator.
    We refer to this as the "display width" of the string.

    This can be useful for formatting text that may contain non-spacing
    characters, or CJK characters that take up two character cells.

    Returns -1 if the string contains a non-printable or control character.

    >>> monospaced_width('ちゃぶ台返し')
    12
    >>> len('ちゃぶ台返し')
    6
    >>> monospaced_width('owl\N{SOFT HYPHEN}flavored')
    12
    >>> monospaced_width('example\x80')
    -1

    A more complex example: The Korean word 'ibnida' can be written with 3
    pre-composed characters or 7 jamo. Either way, it *looks* the same and
    takes up 6 character cells.

    >>> monospaced_width('입니다')
    6
    >>> monospaced_width('\u110b\u1175\u11b8\u1102\u1175\u1103\u1161')
    6
    """
    # NFC-normalize the text first, so that we don't need special cases for
    # Hangul jamo.
    return wcswidth(normalize('NFC', text))
开发者ID:LuminosoInsight,项目名称:python-ftfy,代码行数:32,代码来源:formatting.py

示例8: __str__

    def __str__(self):
        answer = ""
        skip_next = False
        for i, line in enumerate(self.field):
            for j, c in enumerate(line):
                fg_ansi = ""
                bg_ansi = ""
                stop = ""

                if self.field[i][j].foreground:
                    fg_ansi = '\033[38;2;%s;%s;%sm' % rgb_from_str(self.field[i][j].foreground)
                    stop = colored.attr("reset")

                if self.field[i][j].background:
                    bg_ansi = '\033[48;2;%s;%s;%sm' % rgb_from_str(self.field[i][j].background)
                    stop = colored.attr("reset")

                char = c.char or " "
                if not skip_next:
                    answer += fg_ansi + bg_ansi + char.encode('utf-8') + stop
                skip_next = wcswidth(char) == 2

            # answer += "...\n"
            answer += "\n"
        return answer
开发者ID:crazyguitar,项目名称:cheat.sh,代码行数:25,代码来源:panela_colors.py

示例9: _padleft

def _padleft(width, s, has_invisible=True):
    """Flush right.

    >>> _padleft(6, '\u044f\u0439\u0446\u0430') == '  \u044f\u0439\u0446\u0430'
    True

    """
    lwidth = width - wcswidth(_strip_invisible(s) if has_invisible else s)
    return ' ' * lwidth + s
开发者ID:avdd,项目名称:pgcli,代码行数:9,代码来源:tabulate.py

示例10: _padright

def _padright(width, s, has_invisible=True):
    """Flush left.

    >>> _padright(6, '\u044f\u0439\u0446\u0430') == '\u044f\u0439\u0446\u0430  '
    True

    """
    rwidth = width - wcswidth(_strip_invisible(s) if has_invisible else s)
    return s + ' ' * rwidth
开发者ID:avdd,项目名称:pgcli,代码行数:9,代码来源:tabulate.py

示例11: format_value_text

def format_value_text(val, encoding, colormap, quote=False, **_):
    escapedval = val.replace(u'\\', u'\\\\')
    if quote:
        escapedval = escapedval.replace("'", "''")
    escapedval = unicode_controlchars_re.sub(_show_control_chars, escapedval)
    bval = escapedval.encode(encoding, 'backslashreplace')
    if quote:
        bval = "'%s'" % bval

    return bval if colormap is NO_COLOR_MAP else color_text(bval, colormap, wcwidth.wcswidth(bval.decode(encoding)))
开发者ID:MassimoCappellano,项目名称:openshift-origin-cartridge-cassandra,代码行数:10,代码来源:formatting.py

示例12: width_aware_slice

def width_aware_slice(s, start, end, replacement_char=u' '):
    divides = [wcwidth.wcswidth(s, i) for i in range(len(s)+1)]

    new_chunk_chars = []
    for char, char_start, char_end in zip(s, divides[:-1], divides[1:]):
        if char_start >= start and char_end <= end:
            new_chunk_chars.append(char)
        else:
            new_chunk_chars.extend(replacement_char * interval_overlap(char_start, char_end, start, end))

    return ''.join(new_chunk_chars)
开发者ID:sebastinas,项目名称:curtsies,代码行数:11,代码来源:formatstring.py

示例13: _padboth

def _padboth(width, s, has_invisible=True):
    """Center string.

    >>> _padboth(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430 '
    True

    """
    xwidth = width - wcswidth(_strip_invisible(s) if has_invisible else s)
    lwidth = xwidth // 2
    rwidth =  0 if xwidth <= 0 else lwidth + xwidth % 2
    return ' ' * lwidth + s + ' ' * rwidth
开发者ID:avdd,项目名称:pgcli,代码行数:11,代码来源:tabulate.py

示例14: test_combining_enclosing

def test_combining_enclosing():
    u"""CYRILLIC CAPITAL LETTER A + COMBINING CYRILLIC HUNDRED THOUSANDS SIGN is А҈ of length 1."""
    phrase = u"\u0410\u0488"
    expect_length_each = (1, 0)
    expect_length_phrase = 1

    # exercise,
    length_each = tuple(map(wcwidth.wcwidth, phrase))
    length_phrase = wcwidth.wcswidth(phrase, len(phrase))

    # verify,
    assert length_each == expect_length_each
    assert length_phrase == expect_length_phrase
开发者ID:0038lana,项目名称:Test-Task,代码行数:13,代码来源:test_core.py

示例15: test_combining_cafe

def test_combining_cafe():
    u"""Phrase cafe + COMBINING ACUTE ACCENT is café of length 4."""
    phrase = u"cafe\u0301"
    expect_length_each = (1, 1, 1, 1, 0)
    expect_length_phrase = 4

    # exercise,
    length_each = tuple(map(wcwidth.wcwidth, phrase))
    length_phrase = wcwidth.wcswidth(phrase, len(phrase))

    # verify,
    assert length_each == expect_length_each
    assert length_phrase == expect_length_phrase
开发者ID:0038lana,项目名称:Test-Task,代码行数:13,代码来源:test_core.py


注:本文中的wcwidth.wcswidth函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。