• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python wcwidth.wcswidth函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: test_combining_spacing

def test_combining_spacing():
    u"""Balinese kapal (ship) is ᬓᬨᬮ᭄ of length 4."""
    phrase = u"\u1B13\u1B28\u1B2E\u1B44"
    expect_length_each = (1, 1, 1, 1)
    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


示例17: show_top_status

    def show_top_status(self):
        """Show top status row."""
        self.header_win.erase()
        size = self.get_size()
        display = self.app.config["display"]
        head_parts = []
        if display["show_app_name"]:
            name_str = "Suplemon Editor v{0} -".format(self.app.version)
            if self.app.config["app"]["use_unicode_symbols"]:
                logo = "\U0001f34b"  # Fancy lemon
                name_str = " {0} {1}".format(logo, name_str)
            head_parts.append(name_str)

        # Add module statuses to the status bar in descending order
        module_keys = sorted(self.app.modules.modules.keys())
        for name in module_keys:
            module = self.app.modules.modules[name]
            if module.options["status"] == "top":
                status = module.get_status()
                if status:
                    head_parts.append(status)

        if display["show_file_list"]:
            head_parts.append(self.file_list_str())

        head = " ".join(head_parts)
        head = head + (" " * (size[0]-wcswidth(head)-1))
        head_width = wcswidth(head)
        if head_width > size[0]:
            head = head[:size[0]-head_width]
        try:
            if self.app.config["display"]["invert_status_bars"]:
                self.header_win.addstr(0, 0, head, curses.color_pair(0) | curses.A_REVERSE)
            else:
                self.header_win.addstr(0, 0, head, curses.color_pair(0))
        except curses.error:
            pass
        self.header_win.refresh()
开发者ID:twolfson,项目名称:suplemon,代码行数:38,代码来源:ui.py


示例18: test_null_width_0

def test_null_width_0():
    """NULL (0) reports width 0."""
    # given,
    phrase = u'abc\x00def'
    expect_length_each = (1, 1, 1, 0, 1, 1, 1)
    expect_length_phrase = sum(expect_length_each)

    # 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,代码行数:14,代码来源:test_core.py


示例19: test_control_c0_width_negative_1

def test_control_c0_width_negative_1():
    """CSI (Control sequence initiate) reports width -1."""
    # given,
    phrase = u'\x1b[0m'
    expect_length_each = (-1, 1, 1, 1)
    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,代码行数:14,代码来源:test_core.py


示例20: test_combining_width_negative_1

def test_combining_width_negative_1():
    """Simple test combining reports total width of 4."""
    # given,
    phrase = u'--\u05bf--'
    expect_length_each = (1, 1, 0, 1, 1)
    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,代码行数:14,代码来源:test_core.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python wdb.set_trace函数代码示例发布时间:2022-05-26
下一篇:
Python wb_common.dprint_ex函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap