本文整理汇总了Python中textwrap.fill方法的典型用法代码示例。如果您正苦于以下问题:Python textwrap.fill方法的具体用法?Python textwrap.fill怎么用?Python textwrap.fill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textwrap
的用法示例。
在下文中一共展示了textwrap.fill方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cluster_list_to_stream
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def cluster_list_to_stream(self, list_of_cluster, stream=sys.stdout, width=80):
"""
Stream a cluster
@param list_of_cluster: List of internal ids
@type list_of_cluster: list[str|unicode] | dict[str|unicode, str|unicode]
@param stream: File handle or something
@type stream: file | FileIO | StringIO
@param width: Wrap output to a width
@type width: int
@rtype: None
"""
assert self.is_stream(stream)
assert isinstance(list_of_cluster, (dict, list))
if not isinstance(list_of_cluster, dict):
stream.write(textwrap.fill(", ".join(list_of_cluster) + '\n', width))
else:
line = ", ".join('{}: {}'.format(key, value) for key, value in list_of_cluster.items())
stream.write(textwrap.fill(line, width) + '\n')
示例2: _trace_rule
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def _trace_rule(self, rule):
assert self._rule_scores[rule] == sum(self._positions_by_rule[rule].values())
changes = self._positions_by_rule[rule].values()
num_fixed = len([c for c in changes if c == 1])
num_broken = len([c for c in changes if c == -1])
num_other = len([c for c in changes if c == 0])
score = self._rule_scores[rule]
rulestr = rule.format(self._ruleformat)
if self._trace > 2:
print('%4d%4d%4d%4d |' % (score, num_fixed, num_broken, num_other), end=' ')
print(textwrap.fill(rulestr, initial_indent=' '*20, width=79,
subsequent_indent=' '*18+'| ').strip())
else:
print(rulestr)
示例3: pprint_subclasses
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def pprint_subclasses(self, vnclass, indent=''):
"""
Return a string containing a pretty-printed representation of
the given verbnet class's subclasses.
:param vnclass: A verbnet class identifier; or an ElementTree
containing the xml contents of a verbnet class.
"""
if isinstance(vnclass, compat.string_types):
vnclass = self.vnclass(vnclass)
subclasses = [subclass.get('ID') for subclass in
vnclass.findall('SUBCLASSES/VNSUBCLASS')]
if not subclasses: subclasses = ['(none)']
s = 'Subclasses: ' + ' '.join(subclasses)
return textwrap.fill(s, 70, initial_indent=indent,
subsequent_indent=indent+' ')
示例4: pprint_members
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def pprint_members(self, vnclass, indent=''):
"""
Return a string containing a pretty-printed representation of
the given verbnet class's member verbs.
:param vnclass: A verbnet class identifier; or an ElementTree
containing the xml contents of a verbnet class.
"""
if isinstance(vnclass, compat.string_types):
vnclass = self.vnclass(vnclass)
members = [member.get('name') for member in
vnclass.findall('MEMBERS/MEMBER')]
if not members: members = ['(none)']
s = 'Members: ' + ' '.join(members)
return textwrap.fill(s, 70, initial_indent=indent,
subsequent_indent=indent+' ')
示例5: _add_epytext_field
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def _add_epytext_field(obj, field, message):
"""Add an epytext @field to a given object's docstring."""
indent = ''
# If we already have a docstring, then add a blank line to separate
# it from the new field, and check its indentation.
if obj.__doc__:
obj.__doc__ = obj.__doc__.rstrip()+'\n\n'
indents = re.findall(r'(?<=\n)[ ]+(?!\s)', obj.__doc__.expandtabs())
if indents: indent = min(indents)
# If we don't have a docstring, add an empty one.
else:
obj.__doc__ = ''
obj.__doc__ += textwrap.fill('@%s: %s' % (field, message),
initial_indent=indent,
subsequent_indent=indent+' ')
示例6: __call__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def __call__(self, wrapped):
"""
Add the Sphinx directive to your class or function.
:param wrapped: Wrapped class or function.
:return: the decorated class or function.
"""
reason = textwrap.dedent(self.reason).strip()
reason = '\n'.join(textwrap.fill(line, width=70, initial_indent=' ', subsequent_indent=' ')
for line in reason.splitlines()).strip()
docstring = textwrap.dedent(wrapped.__doc__ or "")
if docstring:
docstring += "\n\n"
if self.version:
docstring += ".. {directive}:: {version}\n".format(directive=self.directive, version=self.version)
else:
docstring += ".. {directive}::\n".format(directive=self.directive)
if reason:
docstring += " {reason}\n".format(reason=reason)
wrapped.__doc__ = docstring
return super(SphinxAdapter, self).__call__(wrapped)
示例7: print_sql_error
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def print_sql_error(
model: str,
explore: str,
message: str,
sql: str,
log_dir: str,
dimension: Optional[str] = None,
lookml_url: Optional[str] = None,
) -> None:
path = model + "/"
if dimension:
path += dimension
else:
path += explore
print_header(red(path), LINE_WIDTH + COLOR_CODE_LENGTH)
wrapped = textwrap.fill(message, LINE_WIDTH)
logger.info(wrapped)
if lookml_url:
logger.info("\n" + f"LookML: {lookml_url}")
file_path = log_sql_error(model, explore, sql, log_dir, dimension)
logger.info("\n" + f"Test SQL: {file_path}")
示例8: graph_query_amounts
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def graph_query_amounts(captcha_queries, query_amounts):
queries_and_amounts = zip(captcha_queries, query_amounts)
queries_and_amounts = sorted(queries_and_amounts, key=lambda x:x[1], reverse=True)
captcha_queries, query_amounts = zip(*queries_and_amounts)
# colours = cm.Dark2(np.linspace(0,1,len(captcha_queries)))
# legend_info = zip(query_numbers, colours)
# random.shuffle(colours)
# captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
bars = plt.bar(left=range(len(query_amounts)), height=query_amounts)
plt.xlabel('CAPTCHA queries.')
plt.ylabel('Query frequencies.')
plt.xticks([])
# plt.xticks(range(len(captcha_queries)), captcha_queries, rotation='vertical')
# colours = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', ]
patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
plt.legend(handles=patches)
for i, bar in enumerate(bars):
bar.set_color(colours[i])
plt.show()
示例9: graph_correct_captchas
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def graph_correct_captchas(captcha_queries, correct_captchas):
queries_and_correct_scores = zip(captcha_queries, correct_captchas)
queries_and_correct_scores = sorted(queries_and_correct_scores, key=lambda x:x[1], reverse=True)
captcha_queries, correct_captchas = zip(*queries_and_correct_scores)
captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
bars = plt.bar(left=range(len(correct_captchas)), height=correct_captchas)
patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
plt.legend(handles=patches)
plt.xticks([])
for i, bar in enumerate(bars):
bar.set_color(colours[i])
plt.show()
# graph_correct_captchas(captcha_queries, correct_captchas)
# graph_query_amounts(captcha_queries, query_amounts)
示例10: _pop_header_name
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def _pop_header_name(row, index_col):
"""
Pop the header name for MultiIndex parsing.
Parameters
----------
row : list
The data row to parse for the header name.
index_col : int, list
The index columns for our data. Assumed to be non-null.
Returns
-------
header_name : str
The extracted header name.
trimmed_row : list
The original data row with the header name removed.
"""
# Pop out header name and fill w/blank.
i = index_col if not is_list_like(index_col) else max(index_col)
header_name = row[i]
header_name = None if header_name == "" else header_name
return header_name, row[:i] + [''] + row[i + 1:]
示例11: wrap_function_name
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name
示例12: get_genetic_maps_help
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [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
示例13: __str__
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def __str__(self):
"""Returns a user-readable docstring for this function."""
DOCSTRING_WIDTH = 75
signature = self.getSignature()
parts = []
if 'description' in signature:
parts.append(
textwrap.fill(signature['description'], width=DOCSTRING_WIDTH))
args = signature['args']
if args:
parts.append('')
parts.append('Args:')
for arg in args:
name_part = ' ' + arg['name']
if 'description' in arg:
name_part += ': '
arg_header = name_part + arg['description']
else:
arg_header = name_part
arg_doc = textwrap.fill(arg_header,
width=DOCSTRING_WIDTH - len(name_part),
subsequent_indent=' ' * 6)
parts.append(arg_doc)
return '\n'.join(parts)
示例14: exit_handler
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def exit_handler(self):
indent = ' > '
terminal_width = os.get_terminal_size()[0]
for fileref, path, trace in self.openfiles:
if fileref() and fileref().closed and self.do_print_only_open:
continue
print("-" * terminal_width)
print(" {} = {}".format('path', path))
lines = ''.join(trace).splitlines()
_updated_lines = []
for l in lines:
ul = textwrap.fill(l,
initial_indent=indent,
subsequent_indent=indent,
width=terminal_width)
_updated_lines.append(ul)
lines = _updated_lines
print('\n'.join(lines))
print("-" * terminal_width)
print()
示例15: _handle_request_error
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import fill [as 别名]
def _handle_request_error(self, e):
if isinstance(e, requests.exceptions.RequestException):
msg = ("Unexpected error communicating with Stripe. "
"If this problem persists, let us know at "
"support@stripe.com.")
err = "%s: %s" % (type(e).__name__, str(e))
else:
msg = ("Unexpected error communicating with Stripe. "
"It looks like there's probably a configuration "
"issue locally. If this problem persists, let us "
"know at support@stripe.com.")
err = "A %s was raised" % (type(e).__name__,)
if str(e):
err += " with error message %s" % (str(e),)
else:
err += " with no error message"
msg = textwrap.fill(msg) + "\n\n(Network error: %s)" % (err,)
raise error.APIConnectionError(msg)