python类wrap()的实例源码

filters.py 文件源码 项目:flask_system 作者: prashasy 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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))
test_textwrap.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
tasks.py 文件源码 项目:QProb 作者: quant-trade 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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_
science_articles.py 文件源码 项目:QProb 作者: quant-trade 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
pandoc_imagine.py 文件源码 项目:imagine 作者: hertogp 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:nanostat 作者: wdecoster 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, 80)
search.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
search.py 文件源码 项目:my-first-blog 作者: AnkurBegining 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
optparse.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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)
argparse.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)
prettier.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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 + ')')
prettier.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
table.py 文件源码 项目:python-rst2ansi 作者: Snaipe 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
init.py 文件源码 项目:shub-image 作者: scrapinghub 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
search.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
messaging.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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 ""))
tutor.py 文件源码 项目:fluxpart 作者: usda-ars-ussl 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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')
search.py 文件源码 项目:pip-update-requirements 作者: alanhamlett 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
recipe-580778.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
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)
recipe-577527.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号