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


Python textwrap.TextWrapper类代码示例

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


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


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