Python textwrap 模块,wrap() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用textwrap.wrap()

项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:pscheduler    作者:perfsonar    | 项目源码 | 文件源码
def prefixed_wrap(prefix, text, width=None, indent=0):
    """
    Wrap text with a prefix and optionally indenting the second and
    later lines.  If the width is None, the terminal size will be
    used.  (See terminal_size() for details.)
    """

    if width is None:
        height, width = terminal_size()

    wrapped = textwrap.wrap(text, width - len(prefix))
    leader = " " * (len(prefix) + indent)
    lines = [wrapped.pop(0)]
    lines.extend(["%s%s" % (leader, line)
                  for line in wrapped])

    return "%s%s" % (prefix, "\n".join(lines))
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def say(bot, msg, target, requestor, characters : int = 2000, maxMessage = 5):
    """A helper function to get the bot to cut his text into chunks."""
    if not bot or not msg or not target:
        return False

    textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)

    if not len(textList):
        return False

    if len(textList) > maxMessage and not target == requestor:
        # PM the contents to the requestor
        await bot.send_message(target, "Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
        target = requestor

    for message in textList:
        await bot.send_message(target, message)

    return True
项目:PTE    作者:pwn2winctf    | 项目源码 | 文件源码
def pprint():
    print('')
    print('-'*LINE_WIDTH)
    print('')
    for chall_id in Challenge.index():
        chall = Challenge(chall_id)
        print('ID: %s        (%d points)        [%s]' % (
            chall.id,
            chall['points'],
            ', '.join(chall['tags'])))
        print('')
        print(chall['title'])
        print('')
        print('\n'.join(textwrap.wrap(chall['description'],
                                      LINE_WIDTH)))
        print('')
        print('-'*LINE_WIDTH)
        print('')
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:jarvis    作者:anqxyr    | 项目源码 | 文件源码
def send(bot, text, private=False, notice=False):
    """Send irc message."""
    text = str(text)
    tr = bot._trigger
    jarvis.db.Message.create(
        user=bot.config.core.nick,
        channel=tr.sender,
        time=arrow.utcnow().timestamp,
        text=text)
    mode = 'NOTICE' if notice else 'PRIVMSG'
    recipient = tr.nick if private or notice else tr.sender
    try:
        bot.sending.acquire()
        text = textwrap.wrap(text, width=420)[0]
        bot.write((mode, recipient), text)
    finally:
        bot.sending.release()
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:piqueserver    作者:piqueserver    | 项目源码 | 文件源码
def send_chat(self, value, global_message=False):
        if self.deaf:
            return
        if not global_message:
            chat_message.chat_type = CHAT_SYSTEM
            prefix = ''
        else:
            chat_message.chat_type = CHAT_TEAM
            # 34 is guaranteed to be out of range!
            chat_message.player_id = 35
            prefix = self.protocol.server_prefix + ' '

        lines = textwrap.wrap(value, MAX_CHAT_SIZE - len(prefix) - 1)

        for line in lines:
            chat_message.value = '%s%s' % (prefix, line)
            self.send_contained(chat_message)
项目:sequana    作者:sequana    | 项目源码 | 文件源码
def add_summary_section(self):
        """ Coverage section.
        """
        #image = self.create_embedded_png(self.chromosome.plot_coverage,
        #                              input_arg="filename")

        import textwrap
        command = "\n".join(textwrap.wrap(self.jinja['command'], 80))
        command = self.jinja['command']

        html = "<p>Data type: {}  </p>".format(self.jinja["mode"])
        html += '<div style="textwidth:80%">Command: <pre>{}</pre></div>'.format(command)
        self.sections.append({
            "name": "Data and command used",
            "anchor": "cutadapt",
            "content": html
        })
项目:roguelike-tutorial    作者:Wolfenswan    | 项目源码 | 文件源码
def draw_spotteditems_panel(panel):
    """ draws items below the player a panel """

    # Draw what the player can see at his feet

    spotted = [obj.name for obj in get_items() if (obj.x, obj.y) == gv.player.pos()]
    if len(spotted):  # if more than one object is present, output the names as a message
        x = 2
        y = settings.STAT_PANEL_HEIGHT // 2
        panel.draw_str(x, settings.STAT_PANEL_HEIGHT // 2, 'At your feet:', bg=None, fg=colors.white)
        y += 2
        for obj in spotted:  # Go through the object names and wrap them according to the panel's width
            line_wrapped = wrap(obj, panel.width - 3)
            if y + len(
                    line_wrapped) < panel.height - 2:  # As long as we don't exceed the panel's height, draw the items
                for text in line_wrapped:
                    panel.draw_str(x, y, text, bg=None, fg=colors.white)
                    y += 1
            else:  # otherwise draw a line to indicate there's more than can be displayed
                panel.draw_str((panel.width - 6) // 2, panel.height - 1, '< MORE >')
                break
项目:roguelike-tutorial    作者:Wolfenswan    | 项目源码 | 文件源码
def __init__(self, text, msg_type=MessageType.INFO_GENERIC, log_level=LogLevel.NONCOMBAT, log=None):
        self.text = text
        self.msg_type = msg_type
        self.log_level = log_level

        self.log = log
        if self.log is None:
            self.log = gv.game_log

        self.color = colors.white
        # set messages color
        self.set_color()

        # Format the passed text according to the intended log's width
        self.lines = textwrap.wrap(self.text, self.log.width - 2)

        # Add the Message to the intended log
        self.log.messages.append(self)
项目:RPoint    作者:george17-meet    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:asif    作者:minus7    | 项目源码 | 文件源码
def _help(self, *args, message):
        if len(args) == 0:
            docs = list(self.prefix + key + (f" ({cmd.hint})" if cmd.hint else "")
                for key, cmd in self._commands.items() if key not in ("bots", "help"))
            lines = textwrap.wrap("; ".join(docs), width=400)
            for line in lines:
                if isinstance(message.recipient, Channel):
                    await message.sender.message(line, notice=True)
                else:
                    await message.sender.message(line)
        elif len(args) == 1:
            cmd = self._commands.get(args[0])
            if not cmd:
                return
            if not cmd.doc:
                await message.sender.message(
                        "No help available for that command",
                        notice=True)
            else:
                for line in cmd.doc.split("\n"):
                    await message.sender.message(line, notice=True)
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def print_exception(exc):
    """
    Prints the exception string to StdErr. XML tags are stripped.
    """
    error_string = ""
    if isinstance(exc, Exception):
        if not isinstance(exc, NoTraceException):
            _, _, error_string, _ = get_error_repr(sys.exc_info())
            error_string = "TRACE:\n{}".format(error_string)
        error_string += "ERROR {}: {}\n".format(type(exc).__name__, exc)
    else:
        error_string = exc

    for par in [x.strip(" ") for x in error_string.split("</p>") if x.strip(" ")]:
        par = par.replace("\n", " ").strip(" ")
        par = par.replace("  ", " ")
        print("\n".join(
            textwrap.wrap(re.sub('<[^>]*>', '', par), width=70, replace_whitespace=False)),
            file=sys.stderr)
        print(file=sys.stderr)
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:RealtimePythonChat    作者:quangtqag    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def deprecated(self, msg, version=None, removed=False):
        ''' used to print out a deprecation message.'''

        if not removed and not C.DEPRECATION_WARNINGS:
            return

        if not removed:
            if version:
                new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in version %s." % (msg, version)
            else:
                new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in a future release." % (msg)
            new_msg = new_msg + " Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.\n\n"
        else:
            raise AnsibleError("[DEPRECATED]: %s.\nPlease update your playbooks." % msg)

        wrapped = textwrap.wrap(new_msg, self.columns, replace_whitespace=False, drop_whitespace=False)
        new_msg = "\n".join(wrapped) + "\n"

        if new_msg not in self._deprecations:
            self.display(new_msg.strip(), color=C.COLOR_DEPRECATE, stderr=True)
            self._deprecations[new_msg] = 1
项目:rcli    作者:contains-io    | 项目源码 | 文件源码
def _wrap_section(source, width):
    # type: (str, int) -> str
    """Wrap the given section string to the current terminal size.

    Intelligently wraps the section string to the given width. When wrapping
    section lines, it auto-adjusts the spacing between terms and definitions.
    It also adjusts commands the fit the correct length for the arguments.

    Args:
        source: The section string to wrap.

    Returns:
        The wrapped section string.
    """
    if _get_section('usage', source):
        return _wrap_usage_section(source, width)
    if _is_definition_section(source):
        return _wrap_definition_section(source, width)
    lines = inspect.cleandoc(source).splitlines()
    paragraphs = (textwrap.wrap(line, width, replace_whitespace=False)
                  for line in lines)
    return '\n'.join(line for paragraph in paragraphs for line in paragraph)
项目:rcli    作者:contains-io    | 项目源码 | 文件源码
def _wrap_definition_section(source, width):
    # type: (str, int) -> str
    """Wrap the given definition section string to the current terminal size.

    Note:
        Auto-adjusts the spacing between terms and definitions.

    Args:
        source: The section string to wrap.

    Returns:
        The wrapped section string.
    """
    index = source.index('\n') + 1
    definitions, max_len = _get_definitions(source[index:])
    sep = '\n' + ' ' * (max_len + 4)
    lines = [source[:index].strip()]
    for arg, desc in six.iteritems(definitions):
        wrapped_desc = sep.join(textwrap.wrap(desc, width - max_len - 4))
        lines.append('  {arg:{size}}  {desc}'.format(
            arg=arg,
            size=str(max_len),
            desc=wrapped_desc
        ))
    return '\n'.join(lines)
项目:Indushell    作者:SecarmaLabs    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def wrap_paragraphs(text, ncols=80):
    """Wrap multiple paragraphs to fit a specified width.

    This is equivalent to textwrap.wrap, but with support for multiple
    paragraphs, as separated by empty lines.

    Returns
    -------

    list of complete paragraphs, wrapped to fill `ncols` columns.
    """
    paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
    text = dedent(text).strip()
    paragraphs = paragraph_re.split(text)[::2] # every other entry is space
    out_ps = []
    indent_re = re.compile(r'\n\s+', re.MULTILINE)
    for p in paragraphs:
        # presume indentation that survives dedent is meaningful formatting,
        # so don't fill unless text is flush.
        if indent_re.search(p) is None:
            # wrap paragraph
            p = textwrap.fill(p, ncols)
        out_ps.append(p)
    return out_ps
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def wrap_paragraphs(text, ncols=80):
    """Wrap multiple paragraphs to fit a specified width.

    This is equivalent to textwrap.wrap, but with support for multiple
    paragraphs, as separated by empty lines.

    Returns
    -------

    list of complete paragraphs, wrapped to fill `ncols` columns.
    """
    paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
    text = dedent(text).strip()
    paragraphs = paragraph_re.split(text)[::2] # every other entry is space
    out_ps = []
    indent_re = re.compile(r'\n\s+', re.MULTILINE)
    for p in paragraphs:
        # presume indentation that survives dedent is meaningful formatting,
        # so don't fill unless text is flush.
        if indent_re.search(p) is None:
            # wrap paragraph
            p = textwrap.fill(p, ncols)
        out_ps.append(p)
    return out_ps
项目:SpotifyRadioOrangePiZero    作者:vLX42    | 项目源码 | 文件源码
def displaySpoitfyTitle():

    # Write some text.
    text = "    -=SPOTIFY=-        " +  spconnect('metadata','track_name')  +" - " + spconnect('metadata','artist_name')
    #print text

    lines = textwrap.wrap(text, width=24)
    current_h, pad = 0, 0

    font = ImageFont.load_default()
    font2 = ImageFont.truetype('fonts/C&C Red Alert [INET].ttf', 12)
    with canvas(disp) as draw:
        for line in lines:
            w, h = draw.textsize(line, font=font2)
            draw.text(((128 - w) / 2, current_h), line, font=font2, fill=255)
            current_h += h + pad
项目:flask_system    作者:prashasy    | 项目源码 | 文件源码
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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))
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_category(cat_title):
    cat = wrap(cat_title, 40)[0]
    if settings.SHOW_DEBUG:
        print(colored.green("New category name if changed: {0}".format(cat)))

    try:
        if len(cat) > 0:
            category_ = Category.objects.get(title=cat)
        else:
            category_ = Category.objects.get(title='Unknown')
    except ObjectDoesNotExist:
        if len(cat) > 0:
            category_ = Category.objects.create(title=cat)
        else:
            category_ = Category.objects.create(title='Unknwon')
        category_.save()

    return category_
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def downloader():
        pdfs = ScienceArticle.objects.filter(got_pdf=False)

        for pdf in pdfs:
            source = requests.get(pdf.pdf_url, proxies=settings.PROXIES, headers=settings.HEADERS, timeout=settings.TIMEOUT)

            name = "{0}.pdf".format(wrap(pdf.slug, 60)[0])
            filename = join(settings.BASE_DIR, 'uploads', 'research', name)

            with open(filename, 'wb') as fle:
                print((colored.green("Successfully opened pdf w. path: {0}".format(filename))))
                fle.write(source.content)
                fle.close()

            pdf.file = "uploads/research/{0}".format(name)
            pdf.got_pdf = True
            pdf.save()
项目:imagine    作者:hertogp    | 项目源码 | 文件源码
def image(self, fmt=None):
        'return documentation in a CodeBlock'
        # CodeBlock value = [(Identity, [classes], [(key, val)]), code]
        if not self.code:
            return pf.CodeBlock(('', [], []), __doc__)
        elif self.code == 'classes':
            classes = wrap(', '.join(sorted(Handler.workers.keys())), 78)
            return pf.CodeBlock(('', [], []), '\n'.join(classes))

        doc = []
        for name in self.code.splitlines():
            name = name.lower()
            worker = self.workers.get(name, None)
            doc.append(name)
            if worker is None:
                doc.append('No worker found for %s' % name)
                continue
            if worker.__doc__:
                doc.append(worker.__doc__)
                doc.append('    ' + worker.image.__doc__)
            else:
                doc.append('No help available.')
            doc.append('\n')

        return pf.CodeBlock(('', [], []), '\n'.join(doc))
项目:nanostat    作者:wdecoster    | 项目源码 | 文件源码
def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, 80)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def print_results(hits, name_column_width=None, terminal_width=None):
    if not hits:
        return
    if name_column_width is None:
        name_column_width = max([
            len(hit['name']) + len(hit.get('versions', ['-'])[-1])
            for hit in hits
        ]) + 4

    installed_packages = [p.project_name for p in pkg_resources.working_set]
    for hit in hits:
        name = hit['name']
        summary = hit['summary'] or ''
        version = hit.get('versions', ['-'])[-1]
        if terminal_width is not None:
            target_width = terminal_width - name_column_width - 5
            if target_width > 10:
                # wrap and indent summary to fit terminal
                summary = textwrap.wrap(summary, target_width)
                summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)

        line = '%-*s - %s' % (name_column_width,
                              '%s (%s)' % (name, version), summary)
        try:
            logger.info(line)
            if name in installed_packages:
                dist = pkg_resources.get_distribution(name)
                with indent_log():
                    latest = highest_version(hit['versions'])
                    if dist.version == latest:
                        logger.info('INSTALLED: %s (latest)', dist.version)
                    else:
                        logger.info('INSTALLED: %s', dist.version)
                        logger.info('LATEST:    %s', latest)
        except UnicodeEncodeError:
            pass
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def print_results(hits, name_column_width=None, terminal_width=None):
    if not hits:
        return
    if name_column_width is None:
        name_column_width = max([
            len(hit['name']) + len(hit.get('versions', ['-'])[-1])
            for hit in hits
        ]) + 4

    installed_packages = [p.project_name for p in pkg_resources.working_set]
    for hit in hits:
        name = hit['name']
        summary = hit['summary'] or ''
        version = hit.get('versions', ['-'])[-1]
        if terminal_width is not None:
            target_width = terminal_width - name_column_width - 5
            if target_width > 10:
                # wrap and indent summary to fit terminal
                summary = textwrap.wrap(summary, target_width)
                summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)

        line = '%-*s - %s' % (name_column_width,
                              '%s (%s)' % (name, version), summary)
        try:
            logger.info(line)
            if name in installed_packages:
                dist = pkg_resources.get_distribution(name)
                with indent_log():
                    latest = highest_version(hit['versions'])
                    if dist.version == latest:
                        logger.info('INSTALLED: %s (latest)', dist.version)
                    else:
                        logger.info('INSTALLED: %s', dist.version)
                        logger.info('LATEST:    %s', latest)
        except UnicodeEncodeError:
            pass
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def format_option(self, option):
        # The help for each option consists of two parts:
        #   * the opt strings and metavars
        #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
        #   * the user-supplied help string
        #     eg. ("turn on expert mode", "read data from FILENAME")
        #
        # If possible, we write both of these on the same line:
        #   -x      turn on expert mode
        #
        # But if the opt string list is too long, we put the help
        # string on a second line, indented to the same column it would
        # start in if it fit on the first line.
        #   -fFILENAME, --file=FILENAME
        #           read data from FILENAME
        result = []
        opts = self.option_strings[option]
        opt_width = self.help_position - self.current_indent - 2
        if len(opts) > opt_width:
            opts = "%*s%s\n" % (self.current_indent, "", opts)
            indent_first = self.help_position
        else:                       # start help on same line as opts
            opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
            indent_first = 0
        result.append(opts)
        if option.help:
            help_text = self.expand_default(option)
            help_lines = textwrap.wrap(help_text, self.help_width)
            result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
            result.extend(["%*s%s\n" % (self.help_position, "", line)
                           for line in help_lines[1:]])
        elif opts[-1] != "\n":
            result.append("\n")
        return "".join(result)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)
项目:python-devtools    作者:samuelcolvin    | 项目源码 | 文件源码
def _format_bytes(self, value: bytes, value_repr: str, indent_current: int, indent_new: int):
        wrap = self._width - indent_new - 3
        if len(value) < wrap:
            self._stream.write(value_repr)
        else:
            self._stream.write('(\n')
            prefix = indent_new * self._c
            start, end = 0, wrap
            while start < len(value):
                line = value[start:end]
                self._stream.write(prefix + repr(line) + '\n')
                start = end
                end += wrap
            self._stream.write(indent_current * self._c + ')')
项目:python-devtools    作者:samuelcolvin    | 项目源码 | 文件源码
def _format_raw(self, value: Any, value_repr: str, indent_current: int, indent_new: int):
        lines = value_repr.splitlines(True)
        if len(lines) > 1 or (len(value_repr) + indent_current) >= self._width:
            self._stream.write('(\n')
            wrap_at = self._width - indent_new
            prefix = indent_new * self._c
            for line in lines:
                sub_lines = textwrap.wrap(line, wrap_at)
                for sline in sub_lines:
                    self._stream.write(prefix + sline + '\n')
            self._stream.write(indent_current * self._c + ')')
        else:
            self._stream.write(value_repr)
项目:python-rst2ansi    作者:Snaipe    | 项目源码 | 文件源码
def visit_paragraph(self, node):
    first_line = node.astext().split('\n')[0]

    # handle weird table sizing from simple rst tables
    # disregard cells spanning multiple columns, as
    # these don't contribute to the cell width calculation
    if len(first_line) >= self.width:
        self.width = len(first_line) + 2

    sublines = wrap(node.astext(), width = self.width)
    self.height = int(len(sublines) / self.rows)
    raise nodes.StopTraversal
项目:shub-image    作者:scrapinghub    | 项目源码 | 文件源码
def _wrap(text):
    """Wrap dependencies with separator"""
    lines = textwrap.wrap(text, subsequent_indent='    ',
                          break_long_words=False,
                          break_on_hyphens=False)
    return ' \\\n'.join(lines)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def print_results(hits, name_column_width=25, terminal_width=None):
    installed_packages = [p.project_name for p in pkg_resources.working_set]
    for hit in hits:
        name = hit['name']
        summary = hit['summary'] or ''
        if terminal_width is not None:
            # wrap and indent summary to fit terminal
            summary = textwrap.wrap(summary, terminal_width - name_column_width - 5)
            summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)
        line = '%s - %s' % (name.ljust(name_column_width), summary)
        try:
            logger.notify(line)
            if name in installed_packages:
                dist = pkg_resources.get_distribution(name)
                logger.indent += 2
                try:
                    latest = highest_version(hit['versions'])
                    if dist.version == latest:
                        logger.notify('INSTALLED: %s (latest)' % dist.version)
                    else:
                        logger.notify('INSTALLED: %s' % dist.version)
                        logger.notify('LATEST:    %s' % latest)
                finally:
                    logger.indent -= 2
        except UnicodeEncodeError:
            pass
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def msg(msg, newline=True):
    if TERMWIDTH is None:
        write_outstream(sys.stdout, msg)
        if newline:
            write_outstream(sys.stdout, "\n")
    else:
        # left indent output lines
        lines = textwrap.wrap(msg, TERMWIDTH)
        if len(lines) > 1:
            for line in lines[0:-1]:
                write_outstream(sys.stdout, "  ", line, "\n")
        write_outstream(sys.stdout, "  ", lines[-1], ("\n" if newline else ""))
项目:fluxpart    作者:usda-ars-ussl    | 项目源码 | 文件源码
def quickstart_rawout(field):
    fname = 'quickstart_' + field + '_rawout.txt'
    out = quickstart()
    with open(os.path.join(TXTDIR, fname), 'w') as f:
        f.write(">>> out['{}']\n".format(field))
        for line in textwrap.wrap(out[field].__repr__()):
            f.write(line + '\n')
项目:pip-update-requirements    作者:alanhamlett    | 项目源码 | 文件源码
def print_results(hits, name_column_width=None, terminal_width=None):
    if not hits:
        return
    if name_column_width is None:
        name_column_width = max([
            len(hit['name']) + len(highest_version(hit.get('versions', ['-'])))
            for hit in hits
        ]) + 4

    installed_packages = [p.project_name for p in pkg_resources.working_set]
    for hit in hits:
        name = hit['name']
        summary = hit['summary'] or ''
        latest = highest_version(hit.get('versions', ['-']))
        if terminal_width is not None:
            target_width = terminal_width - name_column_width - 5
            if target_width > 10:
                # wrap and indent summary to fit terminal
                summary = textwrap.wrap(summary, target_width)
                summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)

        line = '%-*s - %s' % (name_column_width,
                              '%s (%s)' % (name, latest), summary)
        try:
            logger.info(line)
            if name in installed_packages:
                dist = pkg_resources.get_distribution(name)
                with indent_log():
                    if dist.version == latest:
                        logger.info('INSTALLED: %s (latest)', dist.version)
                    else:
                        logger.info('INSTALLED: %s', dist.version)
                        logger.info('LATEST:    %s', latest)
        except UnicodeEncodeError:
            pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, master, text, width, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs):   
        if truetype_font is None:
            if font_path is None:
                raise ValueError("Font path can't be None")

            # Initialize font
            truetype_font = ImageFont.truetype(font_path, size)

        lines = textwrap.wrap(text, width=width)

        width = 0
        height = 0

        line_heights = []
        for line in lines:
            line_width, line_height = truetype_font.getsize(line)
            line_heights.append(line_height)

            width = max(width, line_width)
            height += line_height

        image = Image.new("RGBA", (width, height), color=(0,0,0,0))
        draw = ImageDraw.Draw(image)

        y_text = 0
        for i, line in enumerate(lines):
            draw.text((0, y_text), line, font=truetype_font, fill=foreground)
            y_text += line_heights[i]

        self._photoimage = ImageTk.PhotoImage(image)
        Label.__init__(self, master, image=self._photoimage, **kwargs)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, parent, event, callback):
        self.question = textwrap.wrap(event.question, TEXT_WIDTH)
        self.choices = event.choices
        self.answer = event.answer
        self.callback = callback
        super().__init__(parent, event.category)