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


Python textwrap.wrap方法代码示例

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


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

示例1: _wrap_column

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def _wrap_column(
        self, col, column_length, formatter
    ):  # type: (int, List[int], Formatter) -> None
        for i, row in enumerate(self._wrapped_rows):
            cell = row[col]
            cell_length = self._cell_lengths[i][col]

            if cell_length > column_length:
                self._word_wraps = True

                if not self._word_cuts:
                    min_length_without_cut = get_max_word_length(cell, formatter)

                    if min_length_without_cut > column_length:
                        self._word_cuts = True

                # TODO: use format aware wrapper
                wrapped_cell = "\n".join(textwrap.wrap(cell, column_length))

                self._wrapped_rows[i][col] = wrapped_cell

                # Refresh cell length
                self._cell_lengths[i][col] = get_max_line_length(
                    wrapped_cell, formatter
                ) 
开发者ID:sdispater,项目名称:clikit,代码行数:27,代码来源:cell_wrapper.py

示例2: format_info_text

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def format_info_text(text, indent=0, width=70):
    """Return text formatted for readability.
    """
    text = text.strip("\n")
    res = []
    for line in text.splitlines():
        if line.startswith("  "):
            res.append(line)
        elif line.strip() == "":
            res.append(line)
        else:
            res.extend(textwrap.wrap(line, width=width-indent))
    if indent:
        indstr = str(' ' * indent)
        res = list(map(lambda l: indstr + l, res))
    return "\n".join(res) 
开发者ID:mme,项目名称:vergeml,代码行数:18,代码来源:utils.py

示例3: work

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def work(self):
        args = self.cmdline.split(' ')
        command_list = getCmdList()
        if(len(args) > 1):
            cmd = findCmd(args[1])
            if cmd == None:
                log.info("No command with the name: " + args[1])
                return True
            if hasattr(cmd,'parser'):
                cmd.parser.print_help()
            else:
                print(cmd.description)
                print("Aliases: " + " ".join(cmd.keywords))
        else:
            for cmd in command_list:
                print(cmd.keywords[0].ljust(15) + 
                        ("\n" + " "*15).join(textwrap.wrap(cmd.description, 60)))
        return True 
开发者ID:francozappa,项目名称:knob,代码行数:20,代码来源:cmds.py

示例4: get_lines

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def get_lines(self, width=0):
        text = []
        if width == 0:
            return self.text
        for n, i in enumerate(self.text):
            if n in self.idhead:
                text += [i.rjust(width//2 + len(i)//2)] + [""]
            elif n in self.idinde:
                text += ["   "+j for j in textwrap.wrap(i, width - 3)] + [""]
            elif n in self.idbull:
                tmp = textwrap.wrap(i, width - 3)
                text += [" - "+j if j == tmp[0] else "   "+j for j in tmp] + [""]
            elif n in self.idpref:
                tmp = i.splitlines()
                wraptmp = []
                for line in tmp:
                    wraptmp += [j for j in textwrap.wrap(line, width - 6)]
                text += ["   "+j for j in wraptmp] + [""]
            else:
                text += textwrap.wrap(i, width) + [""]
        return text, self.imgs 
开发者ID:wustho,项目名称:epr,代码行数:23,代码来源:epr.py

示例5: _show_syntax

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def _show_syntax(self, msg = None):
		if msg is not None:
			print("Error: %s" % (msg), file = sys.stderr)
		if self._help is not None:
			print()
			for line in textwrap.wrap(self._help):
				print(line)
			print()
		print("Syntax: %s [command] [options]" % (sys.argv[0]), file = sys.stderr)
		print(file = sys.stderr)
		print("Available commands:", file = sys.stderr)
		for commandname in self._cmdorder:
			command = self._commands[commandname]
			print("    %-15s    %s" % (command.name, command.description))
		print(file = sys.stderr)
		print("Options vary from command to command. To receive further info, type", file = sys.stderr)
		print("    %s [command] --help" % (sys.argv[0]), file = sys.stderr) 
开发者ID:johndoe31415,项目名称:joeecc,代码行数:19,代码来源:MultiCommand.py

示例6: _calculate_layout

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def _calculate_layout(self):
        """Setup popup window and format data. """
        self.scr.touchwin()
        self.term_rows, self.term_cols = self.scr.getmaxyx()
        self.box_height = self.term_rows - int(self.term_rows / 2)
        self.win = curses.newwin(int(self.term_rows / 2),
                                 self.term_cols, self.box_height, 0)
        try:
            curses.curs_set(False)
        except _curses.error:
            pass
        # transform raw data into list of lines ready to be printed
        s = self.data.splitlines()
        s = [wrap(i, self.term_cols - 3, subsequent_indent=" ")
             or [""] for i in s]
        self.tdata = [i for j in s for i in j]
        # -3 -- 2 for the box lines and 1 for the title row
        self.nlines = min(len(self.tdata), self.box_height - 3)
        self.scr.refresh() 
开发者ID:OpenTrading,项目名称:OpenTrader,代码行数:21,代码来源:tabview.py

示例7: tokenwrap

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def tokenwrap(tokens, separator=" ", width=70):
    """
    Pretty print a list of text tokens, breaking lines on whitespace

    :param tokens: the tokens to print
    :type tokens: list
    :param separator: the string to use to separate tokens
    :type separator: str
    :param width: the display width (default=70)
    :type width: int
    """
    return '\n'.join(textwrap.wrap(separator.join(tokens), width=width))


##########################################################################
# Python version
########################################################################## 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:19,代码来源:util.py

示例8: re_show

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def re_show(regexp, string, left="{", right="}"):
    """
    Return a string with markers surrounding the matched substrings.
    Search str for substrings matching ``regexp`` and wrap the matches
    with braces.  This is convenient for learning about regular expressions.

    :param regexp: The regular expression.
    :type regexp: str
    :param string: The string being matched.
    :type string: str
    :param left: The left delimiter (printed before the matched substring)
    :type left: str
    :param right: The right delimiter (printed after the matched substring)
    :type right: str
    :rtype: str
    """
    print(re.compile(regexp, re.M).sub(left + r"\g<0>" + right, string.rstrip()))


##########################################################################
# READ FROM FILE OR STRING
##########################################################################

# recipe from David Mertz 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:26,代码来源:util.py

示例9: addText

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def addText(self, text, x = None, fs = None, style = NORMAL):
        if x == None:
            x = self.margin

        if fs == None:
            fs = self.fontSize

        yd = util.getTextHeight(fs)

        if (self.y + yd) > (self.doc.h - self.margin):
            self.createPage()

        self.pg.add(TextOp(text, x, self.y, fs, style))

        self.y += yd

    # wrap text into lines that fit on the page, using Courier and default
    # font size and style, and add the lines. 'indent' is the text to
    # prefix lines other than the first one with. 
开发者ID:trelby,项目名称:trelby,代码行数:21,代码来源:pml.py

示例10: do_wordwrap

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
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)) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:21,代码来源:filters.py

示例11: print_welcome_message

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def print_welcome_message(printer):
    """
    Prints the coala bear logo with a welcome message side by side.

    :param printer:
        A ``ConsolePrinter`` object used for console interaction.
    """
    max_length = 80 - len(max(COALA_BEAR_LOGO, key=len))
    text_lines = ['']
    for welcome_message in WELCOME_MESSAGES:
        text_lines += ['']
        text_lines += textwrap.wrap(welcome_message, max_length)

    print_side_by_side(
        printer,
        left=COALA_BEAR_LOGO,
        right=text_lines,
        limit=80) 
开发者ID:coala,项目名称:coala-quickstart,代码行数:20,代码来源:Logo.py

示例12: formatSchema

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def formatSchema(self):
        """
        Formats the schema source so that we can print it literally
        into a Python source file.
        """
        schema = json.loads(self.schemaSource)
        stack = [schema]
        # Strip out all the docs
        while len(stack) > 0:
            elm = stack.pop()
            if "doc" in elm:
                elm["doc"] = ""
            for value in elm.values():
                if isinstance(value, dict):
                    stack.append(value)
                elif isinstance(value, list):
                    for dic in value:
                        if isinstance(dic, dict):
                            stack.append(dic)
        jsonData = json.dumps(schema)
        # TODO(Greg): Find a long-term solution for making sure the end of the line
        # TODO(Greg): in a schema string is not a - character (dash)
        output = "\n".join(textwrap.wrap(text=jsonData, width=100, break_long_words=False, break_on_hyphens=False)) + "\n"
        return output 
开发者ID:genomicsengland,项目名称:GelReportModels,代码行数:26,代码来源:process_schemas.py

示例13: format_display

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def format_display(display_num, question_text, sent, word, current_guesses,
                   answer=None, guess_limit=5, points=10):
    sep = "".join(["-"] * 80)

    current_text = ""
    for ss in range(sent):
        current_text += "%s " % question_text[ss]
    current_text += " ".join(question_text[sent].split()[:word])
    current_text = "\n".join(textwrap.wrap(current_text, 80))

    report = "Question %i: %i points\n%s\n%s\n%s\n\n" % \
        (display_num, points, sep, current_text, sep)

    for gg in sorted(current_guesses, key=lambda x: current_guesses[x].weight, reverse=True)[:guess_limit]:
        guess = current_guesses[gg]
        if guess.page == answer:
            report += "%-18s\t%-50s\t%0.2f\t%s\n" % (guess.system, "***CORRECT***", guess.weight, guess.evidence[:60])
        else:
            report += "%-18s\t%-50s\t%0.2f\t%s\n" % (guess.system, guess.page, guess.weight, guess.evidence[:60])
    return report 
开发者ID:Pinafore,项目名称:qb,代码行数:22,代码来源:buzzer.py

示例14: _format_raw

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
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

            from textwrap import wrap

            for line in lines:
                sub_lines = 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) 
开发者ID:samuelcolvin,项目名称:python-devtools,代码行数:18,代码来源:prettier.py

示例15: render_row

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import wrap [as 别名]
def render_row(self, target, child=None, **options):
        last_row = self.renderer.table.options.get("last_row")
        if last_row == target:
            return Cell("")

        self.renderer.table.options["last_row"] = target

        if not child:
            child = dict(wrap=False)

        if self.child:
            child_renderer = self.child
        else:
            child_renderer = self.ForTarget(target, renderer=self.renderer)(
                session=self.session, renderer=self.renderer)

        child_cell = child_renderer.render_row(target, **child)
        child_cell.colorizer = self.renderer.colorizer

        return StackedCell(
            Cell("-" * child_cell.width),
            child_cell,
            Cell("-" * child_cell.width),
            table_align=False) 
开发者ID:google,项目名称:rekall,代码行数:26,代码来源:text.py


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