本文整理汇总了Python中textwrap.TextWrapper方法的典型用法代码示例。如果您正苦于以下问题:Python textwrap.TextWrapper方法的具体用法?Python textwrap.TextWrapper怎么用?Python textwrap.TextWrapper使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textwrap
的用法示例。
在下文中一共展示了textwrap.TextWrapper方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _wrap_lines
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def _wrap_lines(lines, wrapper=None):
"""Wraps a multiline string.
Args:
lines: str, a multiline string to wrap.
wrapper: textwrap.TextWrapper, the wrapper to use for wrapping and
formatting.
Returns:
The formatted string.
"""
if wrapper is None:
wrapper = textwrap.TextWrapper(
break_on_hyphens=False,
break_long_words=False,
width=flags.get_help_width())
result = '\n'.join([wrapper.fill(line) for line in lines.splitlines()])
if lines.endswith('\n'):
result += '\n'
return result
示例2: _print_natspec
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def _print_natspec(natspec: Dict) -> None:
wrapper = TextWrapper(initial_indent=f" {color('bright magenta')}")
for key in [i for i in ("title", "notice", "author", "details") if i in natspec]:
wrapper.subsequent_indent = " " * (len(key) + 4)
print(wrapper.fill(f"@{key} {color}{natspec[key]}"))
for key, value in natspec.get("params", {}).items():
wrapper.subsequent_indent = " " * 9
print(wrapper.fill(f"@param {color('bright blue')}{key}{color} {value}"))
if "return" in natspec:
wrapper.subsequent_indent = " " * 10
print(wrapper.fill(f"@return {color}{natspec['return']}"))
for key in sorted(natspec.get("returns", [])):
wrapper.subsequent_indent = " " * 10
print(wrapper.fill(f"@return {color}{natspec['returns'][key]}"))
print()
示例3: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def main(unused_argv):
"""Prints Q&As from modules according to FLAGS.filter."""
init_modules()
text_wrapper = textwrap.TextWrapper(
width=80, initial_indent=' ', subsequent_indent=' ')
for regime, flat_modules in six.iteritems(filtered_modules):
per_module = counts[regime]
for module_name, module in six.iteritems(flat_modules):
# These magic print constants make the header bold.
print('\033[1m{}/{}\033[0m'.format(regime, module_name))
num_dropped = 0
for _ in range(per_module):
problem, extra_dropped = sample_from_module(module)
num_dropped += extra_dropped
text = text_wrapper.fill(
'{} \033[92m{}\033[0m'.format(problem.question, problem.answer))
print(text)
if num_dropped > 0:
logging.warning('Dropped %d examples', num_dropped)
示例4: get_genetic_maps_help
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def get_genetic_maps_help(species_id, genetic_map_id):
"""
Generate help text for the given genetic map. If map_id is None, generate
help for all genetic maps. Otherwise, it must be a string with a valid map
ID.
"""
species = stdpopsim.get_species(species_id)
if genetic_map_id is None:
maps_text = f"\nAll genetic maps for {species.name}\n\n"
maps = [genetic_map.id for genetic_map in species.genetic_maps]
else:
maps = [genetic_map_id]
maps_text = "\nGenetic map description\n\n"
indent = " " * 4
wrapper = textwrap.TextWrapper(initial_indent=indent, subsequent_indent=indent)
for map_id in maps:
gmap = get_genetic_map_wrapper(species, map_id)
maps_text += f"{gmap.id}\n"
maps_text += wrapper.fill(textwrap.dedent(gmap.long_description))
maps_text += "\n\n"
return maps_text
示例5: test_whitespace
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
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))
示例6: __init__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def __init__(self, document, builder):
TextTranslator.__init__(self, document, builder)
newlines = builder.config.text_newlines
if newlines == 'windows':
self.nl = '\r\n'
elif newlines == 'native':
self.nl = os.linesep
else:
self.nl = '\n'
self.sectionchars = builder.config.text_sectionchars
self.states = [[]]
self.stateindent = [0]
self.list_counter = []
self.sectionlevel = 0
self.table = None
if self.builder.config.rst_indent:
self.indent = self.builder.config.rst_indent
else:
self.indent = STDINDENT
self.wrapper = textwrap.TextWrapper(width=STDINDENT, break_long_words=False, break_on_hyphens=False)
示例7: debug_state_string
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def debug_state_string(self):
"""Debug."""
import textwrap
wrapper = textwrap.TextWrapper(subsequent_indent = " ")
output = []
wrapper.initial_indent = "exported rules: "
output.append(wrapper.wrap(", ".join(self._export_rules)))
wrapper.initial_indent = "imported rules: "
output.append(wrapper.wrap(", ".join(self._import_rules)))
wrapper.initial_indent = "lists: "
output.append(wrapper.wrap(", ".join(self._lists)))
wrapper.initial_indent = "words: "
output.append(wrapper.wrap(", ".join(self._words)))
wrapper.initial_indent = "rule definitions: "
output.append(wrapper.wrap(str(self._rule_definitions)))
return "\n".join(["\n".join(lines) for lines in output if lines])
示例8: java_parameter_wrap
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def java_parameter_wrap(value): # pylint: disable=g-bad-name
"""Templatefilter to wrap lines of parameter documentation.
Take a single long string and breaks it up so that subsequent lines are
prefixed by an appropriate number of spaces (and preceded by a ' * '.
Args:
value: (str) the string to wrap
Returns:
the rewrapped string.
"""
# TODO(user): add 'parameter_doc' option to the DocCommentBlock
indent = _language_defaults['java'][_PARAMETER_DOC_INDENT]
prefix = ' * %s ' % (' ' * indent)
wrapper = textwrap.TextWrapper(width=_language_defaults['java'][_LINE_WIDTH],
replace_whitespace=False,
initial_indent='',
subsequent_indent=prefix)
wrapped = wrapper.fill(value)
return wrapped
# We disable the bad function name warning because we use Django style names
# rather than Google style names (disable-msg=C6409)
示例9: __call__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def __call__(self, parser, namespace, values, option_string=None):
# pylint: disable=redefined-outer-name
properties = self._klass.property_list()
width = max(len(prop.__name__) for prop in properties)
wrapper = textwrap.TextWrapper(width=80,
initial_indent=' ', subsequent_indent=' ' * (width + 6))
text = 'Common properties:\n' + '\n'.join(
wrapper.fill('{name:{width}s} {doc}'.format(
name=prop.__name__,
doc=qubes.utils.format_doc(prop.__doc__) if prop.__doc__ else'',
width=width))
for prop in sorted(properties))
if self._klass is not qubes.Qubes:
text += '\n\n' \
'There may be more properties in specific domain classes.\n'
parser.exit(message=text)
示例10: wrap
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def wrap(self, text):
"""Override textwrap.TextWrapper to process 'text' properly when
multiple paragraphs present"""
para_edge = re.compile(r"(\n\s*\n)", re.MULTILINE)
paragraphs = para_edge.split(text)
wrapped_lines = []
for para in paragraphs:
if para.isspace():
if not self.replace_whitespace:
# Do not take the leading and trailing newlines since
# joining the list with newlines (as self.fill will do)
# will put them back in.
if self.expand_tabs:
para = para.expandtabs()
wrapped_lines.append(para[1:-1])
else:
# self.fill will end up putting in the needed newline to
# space out the paragraphs
wrapped_lines.append('')
else:
wrapped_lines.extend(textwrap.TextWrapper.wrap(self, para))
return wrapped_lines
示例11: _info_string_environment
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def _info_string_environment(self, wrapper):
"""Describe environment for :meth:`info_string`.
Args:
wrapper (textwrap.TextWrapper): Helper object for wrapping
text lines if needed.
Returns:
str: Environment information string, or None
"""
if not self.environment_transports:
return None
str_list = ["Environment:"]
wrapper.initial_indent = ' '
wrapper.subsequent_indent = ' '
str_list.extend(wrapper.wrap(
"Transport types: {0}"
.format(" ".join(self.environment_transports))))
return "\n".join(str_list)
示例12: __init__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def __init__(self,source,articleurl):
self.extractorlist=[HuffingtonPost(),NYT(),BBC(),BloomBerg(),Guardian(),TheHindu(),TimesOfIndia()]
websites=ConfigurationReader().GetWebsiteSupported()
self.Mapping={}
for index,website in enumerate(websites):
self.Mapping[website]=self.extractorlist[index]
self.Source=source
self.url=articleurl
self.textWrap=textwrap.TextWrapper(initial_indent='\t',subsequent_indent='\t',width=100)
示例13: __str__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def __str__(self):
struct_name = self.__class__.__name__
raw_hex = _bytes_to_hex(self.pack(), True, hex_per_line=0)
field_strings = []
for name, field in self.fields.items():
# the field header is slightly different for a StructureField
# remove the leading space and put the value on the next line
if isinstance(field, StructureField):
field_header = "%s =\n%s"
else:
field_header = "%s = %s"
field_string = field_header % (field.name, str(field))
field_strings.append(_indent_lines(field_string, TAB))
field_strings.append("")
field_strings.append(_indent_lines("Raw Hex:", TAB))
hex_wrapper = textwrap.TextWrapper(
width=33, # set to show 8 hex values per line, 33 for 8, 56 for 16
initial_indent=TAB + TAB,
subsequent_indent=TAB + TAB
)
field_strings.append(hex_wrapper.fill(raw_hex))
string = "%s:\n%s" % (to_native(struct_name), '\n'.join([to_native(s) for s in field_strings]))
return string
示例14: _print_help
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def _print_help(commands, argv, docstring):
if docstring:
description = inspect.cleandoc(docstring)
sys.stderr.write(description)
sys.stderr.write("\n\n")
sys.stderr.write("Usage:\n")
twc = textwrap.TextWrapper(expand_tabs=True, initial_indent=' ',
subsequent_indent=' ', width=78)
for name, func in sorted(commands.items(), key=lambda x: x[0]):
sys.stderr.write(" %s %s [arg]...\n" %
(os.path.basename(argv[0]), name))
if func.__doc__:
docstring = inspect.cleandoc(func.__doc__)
sys.stderr.write('\n'.join(twc.wrap(docstring)) + '\n')
示例15: _set_cve_plaintext_width
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import TextWrapper [as 别名]
def _set_cve_plaintext_width(self, wrapWidth):
if wrapWidth == 1:
if sys.stdin.isatty():
wrapWidth = self._get_terminal_width() - 2
else:
logger.warning("Stdin redirection suppresses term-width auto-detection; setting WIDTH to 70")
wrapWidth = 70
if wrapWidth:
self.wrapper = textwrap.TextWrapper(width=wrapWidth, initial_indent=" ", subsequent_indent=" ", replace_whitespace=False)
else:
self.wrapper = 0
logger.debug("Set wrapWidth to '{0}'".format(wrapWidth))