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

Python textwrap.TextWrapper类代码示例

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

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



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

示例1: text

 def text(self, text, offset=None, horiz=None, vert=None, *,
 angle=None, font=None, colour=None, width=None):
     attrs = dict()
     style = list()
     transform = list()
     if vert is not None:
         baselines = {
             self.CENTRE: "central",
             self.TOP: "text-before-edge",
             self.BOTTOM: "text-after-edge",
         }
         style.append(("dominant-baseline", baselines[vert]))
     if horiz is not None:
         anchors = {
             self.CENTRE: "middle",
             self.LEFT: "start",
             self.RIGHT: "end",
         }
         style.append(("text-anchor", anchors[horiz]))
     
     transform.extend(self._offset(offset))
     if angle is not None:
         transform.append("rotate({})".format(angle * self.flip[1]))
     
     if font is not None:
         attrs["class"] = font
     attrs.update(self._colour(colour))
     with self.element("text", attrs, style=style, transform=transform):
         if width is None:
             if isinstance(text, str):
                 self.xml.characters(text)
             else:
                 for seg in text:
                     attrs = dict()
                     if seg.get("overline"):
                         attrs["text-decoration"] = "overline"
                     self.tree(("tspan", attrs, (seg["text"],)))
             return
         
         # Very hacky approximation of the size of each character
         # as one en wide
         width /= self.textsize / 2
         wrapper = TextWrapper(width=width, replace_whitespace=False)
         
         hardlines = text.splitlines(keepends=True)
         if not hardlines:
             hardlines.append("")
         line = 0
         for hardline in hardlines:
             wrapped = wrapper.wrap(hardline)
             if not wrapped:  # Caused by empty string
                 wrapped.append("")
             for softline in wrapped:
                 lineattrs = {
                     "x": "0",
                     "y": "{}em".format(line / 0.875),
                     "xml:space": "preserve",
                 }
                 self.tree(("tspan", lineattrs, (softline,)))
                 line += 1
开发者ID:gastonfeng,项目名称:python-altium,代码行数:60,代码来源:svg.py


示例2: __classrepr__

    def __classrepr__(cls):
        """
        Note: ipython3 doesn't seem to render class reprs correctly -- may be
        a bug in the beta version I used. Looks fine in python3 and ipython2.

        """

        def field_items(field_list):
            return list((attr, getattr(cls, attr, "")) for attr in field_list)

        def format_fields(field_list):
            s = ", ".join(
                "{field}={value!r}".format(field=field.lower(), value=value)
                for field, value in field_items(field_list)
                if not value  # show only fields without default values
            )
            return s + "," if s else "# <none>"

        textwrapper = TextWrapper(initial_indent=" " * 4, subsequent_indent=" " * 4)
        l = []
        l.append("\n{cls.__name__}(".format(cls=cls))
        l.append("    # Required fields")
        l.append(textwrapper.fill(format_fields(cls._required)))
        if getattr(cls, "_conditional", None):
            for label, fields in cls._conditional.items():
                l.append("\n    # Required if using " + label)
                l.append(textwrapper.fill(format_fields(fields)))
        if cls._discretionary_data_allowed is True:
            l.append("\n    " "# Customer-defined discretionary data may also be included.")
        l.append("\n    # Optional fields")
        l.append(textwrapper.fill(format_fields(cls._optional)))
        l.append(")\n")
        return "\n".join(l)
开发者ID:jdnier,项目名称:paytrace,代码行数:33,代码来源:paytrace.py


示例3: fill

def fill(output_str, indent = "    "):
    from textwrap import TextWrapper
    console_width = get_console_width()
    wrapper = TextWrapper(initial_indent    = indent,
                          subsequent_indent = indent,
                          width = console_width)
    return wrapper.fill(output_str)
开发者ID:penguian,项目名称:glucat,代码行数:7,代码来源:pyclical_tutorial_utils.py


示例4: _split_body

    def _split_body(self, text_lines):
        """Split the body into summary and details.

        This will assign to self.body_summary the summary text, but it will
        return the details text for further santization.

        :return: the raw details text.
        """
        # If there are no non-blank lines, then we're done.
        if len(text_lines) == 0:
            self.body_summary = u''
            return u''
        # If the first line is of a completely arbitrarily chosen reasonable
        # length, then we'll just use that as the summary.
        elif len(text_lines[0]) < 60:
            self.body_summary = text_lines[0]
            return u'\n'.join(text_lines[1:])
        # It could be the case that the text is actually flowed using RFC
        # 3676 format="flowed" parameters.  In that case, just split the line
        # at the first whitespace after, again, our arbitrarily chosen limit.
        else:
            first_line = text_lines.pop(0)
            wrapper = TextWrapper(width=60)
            filled_lines = wrapper.fill(first_line).splitlines()
            self.body_summary = filled_lines[0]
            text_lines.insert(0, u''.join(filled_lines[1:]))
            return u'\n'.join(text_lines)
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:27,代码来源:mailinglists.py


示例5: test_whitespace

    def test_whitespace(self):
        # Whitespace munging and end-of-sentence detection

        text = """\
This is a paragraph that already has
line breaks.  But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""

        expect = [
            "This is a paragraph that already has line",
            "breaks.  But some of its lines are much",
            "longer than the others, so it needs to be",
            "wrapped.  Some lines are  tabbed too.  What a",
            "mess!",
        ]

        wrapper = TextWrapper(45, fix_sentence_endings=True)
        result = wrapper.wrap(text)
        self.check(result, expect)

        result = wrapper.fill(text)
        self.check(result, "\n".join(expect))
开发者ID:Jarga,项目名称:IBM-Innovate-2012,代码行数:25,代码来源:test_textwrap.py


示例6: print_error

def print_error(fname, line_number, err_msg):
    header = "Error in file {0}, line {1}:".format(fname, line_number + 1)

    tw = TextWrapper(width=80, initial_indent=' '*4, subsequent_indent=' '*4)
    body = '\n'.join(tw.wrap(err_msg))

    print(header + '\n' + body + '\n')
开发者ID:LMKerby,项目名称:openmc,代码行数:7,代码来源:check_source.py


示例7: settings

    def settings(self, short=None):
        """List available settings."""
        types = {v: k for k, v in TYPE_CLASSES.items()}
        wrapper = TextWrapper(initial_indent='# ', subsequent_indent='# ')
        for i, section in enumerate(sorted(self._settings)):
            if not short:
                print('%s[%s]' % ('' if i == 0 else '\n', section))

            for option in sorted(self._settings[section]._settings):
                meta = self._settings[section].get_meta(option)
                desc = meta['description']

                if short:
                    print('%s.%s -- %s' % (section, option, desc.splitlines()[0]))
                    continue

                if option == '*':
                    option = '<option>'

                if 'choices' in meta:
                    value = "{%s}" % ', '.join(meta['choices'])
                else:
                    value = '<%s>' % types[meta['type_cls']]

                print(wrapper.fill(desc))
                print(';%s=%s' % (option, value))
开发者ID:luke-chang,项目名称:gecko-1,代码行数:26,代码来源:settings.py


示例8: report

def report(trans, html=False):
    """Returns a summary report of all of the transactions."""
    invs = inventories(trans)
    rankings = []
    for player, inv in invs.items():
        rankings.append((player, inv['cones'], inv['magic']))
    rankings.sort(key=lambda x: x[1], reverse=True)
    listings = []
    tw = TextWrapper(width=30)
    mctemp = '{1}x {0} cone{2}'
    for player, cones, magic in rankings:
        s = ', '.join([mctemp.format(key, value, '' if value == 1 else 's') \
                       for key, value in sorted(magic.items()) if value > 0])
        s = '\n'.join(tw.wrap(s))
        listings.append((player, 
                         cones // CONES_PER_TREE or '', 
                         (cones // CONES_PER_SAPLING) % (CONES_PER_TREE // CONES_PER_SAPLING) or \
                            ('' if cones // CONES_PER_TREE == 0 else 0), 
                         cones % CONES_PER_SAPLING,
                         s,
                         ))
    tab = PrettyTable(['Player', 'Trees', 'Saplings', 'Cones', 'Magic Cones'])
    for listing in listings:
        tab.add_row(listing)
    rep = tab.get_html_string(format=True) if html else tab.get_string()
    return rep
开发者ID:pyne,项目名称:magic-cones,代码行数:26,代码来源:report.py


示例9: msg

def msg(text, sep=' ', *args, **kwargs):
    '''
    A convenience to neatly format message strings, such as error messages.
    '''

    text_wrapper = TextWrapper(*args, **kwargs)
    return sep.join(text_wrapper.wrap(text.strip()))
开发者ID:lawsofthought,项目名称:wilhelmproject,代码行数:7,代码来源:strings.py


示例10: format

 def format(self, **kargs):
     self.parse()
     if self._package_name is not None:
         kargs['package_name'] = self._package_name
     if 'version' not in kargs:
         if len(self.logs) > 0:
             version = self.logs[0]['version']
             reobj = re.match(r"""(.*)(\d+)$""", version)
             if reobj is None:
                 version += '~1'
             else:
                 version = reobj.group(1) + str(int(reobj.group(2)) + 1)
         else:
             version = '1.0'
         kargs['version'] = version
     title = '{package_name} ({version})'.format(**kargs)
     messages = '  * '
     wrapper = TextWrapper(width=80, initial_indent='  * ',
                           subsequent_indent='    ')
     if 'messages' in kargs:
         messages = []
         for message in kargs['messages']:
             messages.append(wrapper.fill(message))
         messages = '\n'.join(messages)
     kargs['time'] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
     tailer = ' -- {author} <{email}>  {time}'.format(**kargs)
     return title + '\n\n' + messages + '\n\n' + tailer + '\n\n'
开发者ID:qnap-dev,项目名称:qdk2,代码行数:27,代码来源:controlfiles.py


示例11: print_arguments

def print_arguments(arguments, width=None):
    if width == None:
        width = 0
        for arg in arguments:
            width = max(width, len(get_option_names(arg)))

    help_wrapper = TextWrapper(
        width=terminal_width,
        initial_indent=' ' * (width + 5),
        subsequent_indent=' ' * (width + 5),
        )

    return ('\n'.join(
        ' ' * 2 + '{0:<{width}}  {1}'.format(
            get_option_names(arg),
            help_wrapper.fill(
                arg.help +
                    (
                    _('(default: {0})').format(arg.default)
                        if arg.default not in (None, False)
                    else _('(required)')
                        if not (arg.optional or arg.positional)
                    else ''

                    )
            )[width + 4:]
                if arg.help else '',
            width=width,
        ) for arg in arguments))
开发者ID:nicolargo,项目名称:clize,代码行数:29,代码来源:clize.py


示例12: wrap_for_make

def wrap_for_make(items):
    line = join(sorted(items))
    wrapper = TextWrapper()
    wrapper.width = 60
    wrapper.break_on_hyphens = False
    wrapper.subsequent_indent = '\t' * 2
    return ' \\\n'.join(wrapper.wrap(line))
开发者ID:handsomegui,项目名称:mpd-win32-build,代码行数:7,代码来源:buildtool.py


示例13: CppEvaluations

    def CppEvaluations(self, Indent=4):
        """Evaluate all derived variables in C++

        This function uses the `substitution` expressions for the
        derived variables.  This output is appropriate for updating
        the values of the variables at each step of an integration,
        for example.

        """
        from textwrap import TextWrapper
        wrapper = TextWrapper(width=120)
        wrapper.initial_indent = ' '*Indent
        wrapper.subsequent_indent = wrapper.initial_indent + '  '
        def Evaluation(atom):
            def Ccode(a) :
                try:
                    return a.ccode()
                except :
                    from sympy.printing import ccode
                    return ccode(a)
            if atom.datatype and (atom.datatype=='std::vector<double>' or atom.datatype=='std::vector<std::complex<double> >') :
                return '\n'.join([wrapper.fill('{0}[{1}] = {2};'.format(self.Variables[atom], i, Ccode(atom.substitution[i])))
                                  for i in range(len(atom.substitution))])
            else:
                return wrapper.fill('{0} = {1};'.format(self.Variables[atom], atom.ccode()))
        return '\n'.join([Evaluation(atom) for atom in self.Atoms if not atom.fundamental and not atom.constant])
开发者ID:moble,项目名称:PostNewtonian,代码行数:26,代码来源:CodeOutput.py


示例14: CppInitializations

    def CppInitializations(self, Indent=4):
        """Create initialization list for C++

        For example, if the `Variables` object contains atoms m1, m2,
        t, and x referred to in the `Expressions` object, where m1 and
        m2 are constant, and t and x are variables, the initialization
        list should be

            m1(m1_i), m2(m2_i), t(t_i), x(x_i)

        The quantities m1_i, etc., appear in the input-argument list
        output by the method `CppInputArguments`.

        """
        from textwrap import TextWrapper
        wrapper = TextWrapper(width=120)
        wrapper.initial_indent = ' '*Indent
        wrapper.subsequent_indent = wrapper.initial_indent
        def Initialization(atom):
            if atom.datatype and (atom.datatype=='std::vector<double>' or atom.datatype=='std::vector<std::complex<double> >'):
                return '{0}({1})'.format(self.Variables[atom], len(atom.substitution))
            if atom.fundamental:
                return '{0}({0}_i)'.format(self.Variables[atom])
            else:
                return '{0}({1})'.format(self.Variables[atom], atom.ccode())
        Initializations  = [Initialization(atom) for atom in self.Atoms]
        return wrapper.fill(', '.join(Initializations))
开发者ID:moble,项目名称:PostNewtonian,代码行数:27,代码来源:CodeOutput.py


示例15: quote_text_as_email

def quote_text_as_email(text, width=80):
    """Quote the text as if it is an email response.

    Uses '> ' as a line prefix, and breaks long lines.

    Trailing whitespace is stripped.
    """
    # Empty text begets empty text.
    if text is None:
        return ''
    text = text.rstrip()
    if not text:
        return ''
    prefix = '> '
    # The TextWrapper's handling of code is somewhat suspect.
    wrapper = TextWrapper(
        initial_indent=prefix,
        subsequent_indent=prefix,
        width=width,
        replace_whitespace=False)
    result = []
    # Break the string into lines, and use the TextWrapper to wrap the
    # individual lines.
    for line in text.rstrip().split('\n'):
        # TextWrapper won't do an indent of an empty string.
        if line.strip() == '':
            result.append(prefix)
        else:
            result.extend(wrapper.wrap(line))
    return '\n'.join(result)
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:30,代码来源:codereviewcomment.py


示例16: wrap

def wrap(text, width=77, indent='', long_words=False, hyphens=False):
    """
    Wrap text for cleaner output (this is a simple wrapper around
    ``textwrap.TextWrapper`` in the standard library).

    Args:
        text (str): The text to wrap

    Keyword Arguments:
        width (int): The max width of a line before breaking
        indent (str): String to prefix subsequent lines after breaking
        long_words (bool): Whether or not to break on long words
        hyphens (bool): Whether or not to break on hyphens

    Returns:
        str: The wrapped string

    """

    types = [str]
    if type(text) not in types:
        raise TypeError("Argument `text` must be one of [str, unicode].")

    wrapper = TextWrapper(subsequent_indent=indent, width=width,
                          break_long_words=long_words,
                          break_on_hyphens=hyphens)
    return wrapper.fill(text)
开发者ID:datafolklabs,项目名称:cement,代码行数:27,代码来源:misc.py


示例17: _stream_formatter

    def _stream_formatter(self, record):
        """The formatter for standard output."""
        if record.levelno < logging.DEBUG:
            print(record.levelname, end='')
        elif(record.levelno < logging.INFO):
            colourPrint(record.levelname, 'green', end='')
        elif(record.levelno < IMPORTANT):
            colourPrint(record.levelname, 'magenta', end='')
        elif(record.levelno < logging.WARNING):
            colourPrint(record.levelname, 'lightblue', end='')
        elif(record.levelno < logging.ERROR):
            colourPrint(record.levelname, 'brown', end='')
        else:
            colourPrint(record.levelname, 'red', end='')

        if record.levelno == logging.WARN:
            message = '{0}'.format(record.msg[record.msg.find(':')+2:])
        else:
            message = '{0}'.format(record.msg)

        if len(message) > self.wrapperLength:
            tw = TextWrapper()
            tw.width = self.wrapperLength
            tw.subsequent_indent = ' ' * (len(record.levelname)+2)
            tw.break_on_hyphens = False
            message = '\n'.join(tw.wrap(message))

        print(': ' + message)
开发者ID:ApachePointObservatory,项目名称:Totoro,代码行数:28,代码来源:logger.py


示例18: dict_str

 def dict_str(self):
    """Build a human-readable definition for this word, including data for each synset"""
    tw = TextWrapper(width=self.LINE_WIDTH_MAX,
       initial_indent=(self.prefix_fmtf_line_first % self.category_map_rev[self.category]),
       subsequent_indent=(self.prefix_fmtn_line_first % (len(self.category_map_rev[self.category]), '')))
       
    lines = (tw.wrap(self.synsets[0].synset_get().dict_str()))
    i = 2
    
    prefix_fmtn_line_nonfirst = self.prefix_fmtn_line_nonfirst
    pfln_len = 0
    for ss_wrap in self.synsets[1:]:
       # adjust indenting based on index-number with
       pfln_len_new = len('%d' % (i,))
       if (pfln_len_new > pfln_len):
          pfln_len = pfln_len_new
          pfln_str = (self.prefix_fmtn_line_nonfirst % (pfln_len, ''))
       
       # format data for this synset
       synset = ss_wrap.synset_get()
       tw = TextWrapper(width=self.LINE_WIDTH_MAX,
          initial_indent=(self.prefix_fmtf_line_nonfirst % i),
          subsequent_indent=pfln_str)
       lines.extend(tw.wrap(synset.dict_str()))
       
       i += 1
       
    return self.linesep.join(lines)
开发者ID:OpenMandrivaAssociation,项目名称:dictd-dicts-wn,代码行数:28,代码来源:wordnet_structures.py


示例19: refill

def refill(msg):
    """
    Refill a changelog message.

    Normalize the message reducing multiple spaces and newlines to single
    spaces, recognizing common form of ``bullet lists``, that is paragraphs
    starting with either a dash "-" or an asterisk "*".
    """

    wrapper = TextWrapper()
    res = []
    items = itemize_re.split(msg.strip())

    if len(items)>1:
        # Remove possible first empty split, when the message immediately
        # starts with a bullet
        if not items[0]:
            del items[0]

        if len(items)>1:
            wrapper.initial_indent = '- '
            wrapper.subsequent_indent = ' '*2

    for item in items:
        if item:
            words = filter(None, item.strip().replace('\n', ' ').split(' '))
            normalized = ' '.join(words)
            res.append(wrapper.fill(normalized))

    return '\n\n'.join(res)
开发者ID:c0ns0le,项目名称:cygwin,代码行数:30,代码来源:changes.py


示例20: list_posts

def list_posts(discussions):
        t = PrettyTable([
            "identifier",
            "title",
            "category",
            "replies",
            # "votes",
            "payouts",
        ])
        t.align = "l"
        t.align["payouts"] = "r"
        # t.align["votes"] = "r"
        t.align["replies"] = "c"
        for d in discussions:
            identifier = "@%s/%s" % (d["author"], d["permlink"])
            identifier_wrapper = TextWrapper()
            identifier_wrapper.width = 60
            identifier_wrapper.subsequent_indent = " "

            t.add_row([
                identifier_wrapper.fill(identifier),
                identifier_wrapper.fill(d["title"]),
                d["category"],
                d["children"],
                # d["net_rshares"],
                d["pending_payout_value"],
            ])
        print(t)
开发者ID:PixelNoob,项目名称:piston,代码行数:28,代码来源:ui.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python textx.metamodel_from_str函数代码示例发布时间:2022-05-27
下一篇:
Python textwrap.wrap函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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