本文整理匯總了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
)
示例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)
示例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
示例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
示例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)
示例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()
示例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
##########################################################################
示例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
示例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.
示例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))
示例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)
示例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
示例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
示例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)
示例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)