本文整理汇总了Python中textwrap.TextWrapper.fill方法的典型用法代码示例。如果您正苦于以下问题:Python TextWrapper.fill方法的具体用法?Python TextWrapper.fill怎么用?Python TextWrapper.fill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textwrap.TextWrapper
的用法示例。
在下文中一共展示了TextWrapper.fill方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: display_search_results
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def display_search_results(self, mixes, s):
if self._search_results_page < self.total_pages:
next_notification = "--Next-- (Enter)"
else:
next_notification = ""
print('Results for "{}":'.format(s))
wrapper = TextWrapper(width=self.console_width - 5, subsequent_indent=(' ' * 5))
mix_info_tpl = Template('$name ($trackcount tracks, ${hours}h ${minutes}m, by ${user})')
page_info_tpl = Template('Page $page on $total_pages. $next_notification')
# If this is a new query, reset mixes dictionary
if self._search_results_page == 0:
self.mixes = {}
# Store and show new mix results
start_page_no = (self._search_results_page - 1) * self.config['results_per_page'] + 1
for i, mix in enumerate(mixes, start_page_no):
# Cache mix
self.mixes[i] = mix
# Print line
prefix = ' {0})'.format(i).ljust(5)
hours = mix['duration'] // 60 // 60
minutes = (mix['duration'] // 60) % 60
mix_info = mix_info_tpl.substitute(name=bold(mix['name']), user=mix['user']['login'],
trackcount=mix['tracks_count'], hours=hours, minutes=minutes)
print(prefix + wrapper.fill(mix_info))
print(wrapper.fill(' Tags: {}'.format(mix['tag_list_cache'])))
page_info = page_info_tpl.substitute(page=bold(str(self._search_results_page)),
total_pages=bold(str(self.total_pages)), next_notification=next_notification)
print(wrapper.fill(page_info))
示例2: show_cache
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def show_cache(definer):
from textwrap import TextWrapper
import inflection
def singular_plural(n, word):
if word == 0:
return ('no', inflection.pluralize(word))
elif word == 1:
return (1, word)
else:
return (str(n), inflection.pluralize(word))
cache_file = definer.cache_file
if cache_file is None:
print("Caching is not enabled.")
else:
words = sorted(definer.cache.keys())
n = len(words)
wrapper = TextWrapper(width=WRAP_WIDTH)
print(wrapper.fill(
'Definition cache "{0}" contains {1} {2}.'.format(
cache_file, *singular_plural(n, 'word')
))
)
if n > 0:
print('\n' + wrapper.fill(', '.join(words)))
示例3: Wrapper
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
class Wrapper(object):
#: What to break the words on. It is based on the one inside the
#: :class:`textwrap.TextWrapper` class, but without the breaking on '-'.
splitExp = re_compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))')
#: How to identify quotes
quoteExp = re_compile(r'(>+\ +)')
def __init__(self, width):
self.email_wrapper = TextWrapper(
width=width, expand_tabs=False, replace_whitespace=False, break_on_hyphens=False,
break_long_words=False)
self.email_wrapper.wordsep_re = self.splitExp
self.quote_wrapper = TextWrapper(
expand_tabs=False, replace_whitespace=False, break_on_hyphens=False,
break_long_words=False)
self.quote_wrapper.wordsep_re = self.splitExp
def wrap_line(self, l):
m = self.quoteExp.match(l)
if m:
# Quotation wrap
quoteChars = m.group(1)
self.quote_wrapper.subsequent_indent = quoteChars
retval = self.quote_wrapper.fill(l)
else:
# Normal wrap
retval = self.email_wrapper.fill(l)
return retval
示例4: help
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def help(name, command, just_do_usage=False, do_print=True, **kwargs):
ret = ""
ret += (_('Usage: {0}{1} {2}').format(
name,
command.options and _(' [OPTIONS]') or '',
' '.join(get_arg_name(arg) for arg in command.posargs),
))
if just_do_usage:
if do_print:
print(ret)
return ret
tw = TextWrapper(
width=get_terminal_width()
)
ret += '\n\n'.join(
tw.fill(p) for p in ('',) + command.description) + '\n'
if command.posargs:
ret += '\n' + _('Positional arguments:') + '\n'
ret += print_arguments(command.posargs) + '\n'
if command.options:
ret += '\n' + _('Options:') + '\n'
ret += print_arguments(command.options) + '\n'
if command.footnotes:
ret += '\n' + '\n\n'.join(tw.fill(p) for p in command.footnotes)
ret += '\n'
if do_print:
print(ret)
return ret
示例5: describe
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def describe(self):
if self.app.cloudlet_name is None or self.app.blueprint_name is None:
print "Usage: nepho blueprint describe <cloudlet> <blueprint>"
exit(1)
else:
scope.print_scope(self)
c = _load_cloudlet(self, self.app.cloudlet_name)
bp = c.blueprint(self.app.blueprint_name)
if bp is None:
print colored("Error: ", "red"), "No blueprint by that name.\nFor a list of blueprints run `nepho blueprint list %s`" % (self.app.cloudlet_name)
exit(1)
wrapper = TextWrapper(width=80, initial_indent=" ", subsequent_indent=" ")
wrapper2 = TextWrapper(width=80, initial_indent=" ", subsequent_indent=" ")
if bp.definition is not None:
print colored(" " + base.DISP_PATH, "yellow"), colored(bp.name, attrs=['underline']), "[", colored(bp.definition['provider'], 'magenta'), "]"
print wrapper.fill(bp.definition['summary'])
else:
print colored(" " + base.DISP_PATH, "yellow"), colored(bp.name, attrs=['underline'])
print colored(" Error - missing or malformed blueprint.yaml", "red")
return
print "\n Description:"
print wrapper2.fill(bp.definition['description'])
print "\n Default Parameters:"
params = bp.definition.pop('parameters', None)
for k, v in params.iteritems():
print " %-18s: %s" % (k, v)
print
return
示例6: __classrepr__
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def __classrepr__(cls):
"""
Note: ipython3 doesn't seem to render class reprs correctly -- may be
a bug in the beta version I used. Looks fine in python3 and ipython2.
"""
def field_items(field_list):
return list((attr, getattr(cls, attr, "")) for attr in field_list)
def format_fields(field_list):
s = ", ".join(
"{field}={value!r}".format(field=field.lower(), value=value)
for field, value in field_items(field_list)
if not value # show only fields without default values
)
return s + "," if s else "# <none>"
textwrapper = TextWrapper(initial_indent=" " * 4, subsequent_indent=" " * 4)
l = []
l.append("\n{cls.__name__}(".format(cls=cls))
l.append(" # Required fields")
l.append(textwrapper.fill(format_fields(cls._required)))
if getattr(cls, "_conditional", None):
for label, fields in cls._conditional.items():
l.append("\n # Required if using " + label)
l.append(textwrapper.fill(format_fields(fields)))
if cls._discretionary_data_allowed is True:
l.append("\n " "# Customer-defined discretionary data may also be included.")
l.append("\n # Optional fields")
l.append(textwrapper.fill(format_fields(cls._optional)))
l.append(")\n")
return "\n".join(l)
示例7: usage
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def usage(self):
tw = TextWrapper(
width=78,
drop_whitespace=True,
expand_tabs=True,
fix_sentence_endings=True,
break_long_words=True,
break_on_hyphens=True,
)
text = tw.fill(self.__doc__.strip()) + "\n\n"
try:
options = self.pluginOptions
except AttributeError:
return text + "This plugin does not support any options.\n"
tw.subsequent_indent=' ' * 16,
text += "Options supported by this plugin:\n"
for opt in sorted(options.keys()):
text += "--opt={:<12} ".format(opt)
text += tw.fill(options[opt].strip()) + "\n"
text += "\n"
text += "You can also chain options together, e.g.:\n"
text += " --opt=systems,stations,csvonly\n"
return text
示例8: _list_verbose
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def _list_verbose(self, migration):
if self.verbose:
lead = ' ' * 5
wrap = TextWrapper(width=80, initial_indent=lead, subsequent_indent=lead)
meta = migration.meta
if meta:
self.console()
for field in ('Author', 'link', 'Description'):
value = meta.get(field)
if value:
self.console(lead + defaultfilters.title(field) + ': ' + value)
if migration.flagged:
self.console()
self.console(lead + 'Flagged: True', 'red')
message = meta.get('flag_message')
if message:
self.console(wrap.fill(message))
last_run = migration.last_run
if last_run:
meta = last_run.meta
if last_run.meta:
self.console()
meta['date'] = self._local_datetime(last_run.create_date)
for field in ('runner', 'date'):
value = last_run.meta.get(field)
if value:
self.console(lead + defaultfilters.title(field) + ': ' + value)
notes = meta.get('notes')
if notes:
self.console(wrap.fill(notes))
if meta or last_run:
self.console()
示例9: __init__
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
class Parser:
"""
Основной разбор происходит в этом классе, при создании экземпляра класса
так же задаются глобальные настройки. При помощи внутреннего парсера
разбираем страницу, находим див который содержит больше всего дивов в себе
и отдаем его как контент статьи.
Для работы обязательно нужно задать настройки для домена
"""
def __init__(self, raw_data, settings):
self.page = raw_data
self.settings = settings
self.wrapper = TextWrapper(width=self.settings.get('text_width'))
self.__parsed_title = None
self.__parsed_content = None
self.prepare()
def prepare(self):
removed_tags = [
'script',
'aside',
'header',
'style',
'nav',
'section',
'footer',
'noindex',
]
result = self.page
for tag in removed_tags:
rx = "<{0}[\s\S]+?/{0}>".format(tag)
pattern = re.compile(rx)
result = re.sub(pattern, '', result)
pattern_link = re.compile(r'<a\s+[^>]*?href="([^"]*)".*?>(.*?)<\/a>', re.DOTALL)
result = pattern_link.sub(r'\2[\1]', result)
inner_parser = HTMLSourceParser()
inner_parser.feed(result)
inner_parser.close()
divs = {k: len(v) for k, v in inner_parser.div_data.items()}
max_divs = max(divs.items(), key=operator.itemgetter(1))[0]
self.__parsed_title = inner_parser.header_data[0]
self.__parsed_content = inner_parser.div_data[max_divs]
def get_title(self):
self.wrapper.initial_indent = ""
return self.wrapper.fill(self.__parsed_title)
def get_article_body(self):
text = ''
self.wrapper.initial_indent = self.settings.get('article_indent')
for paragraph in self.__parsed_content:
text += self.wrapper.fill(paragraph)
return text
示例10: plot_list
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def plot_list(self):
"""Lists the names of the available figures"""
wrapper = TextWrapper(subsequent_indent = " " * 22,
width = 78)
for method, func in self.get_available_figures():
if method != "list":
wrapper.initial_indent = ("%-20s " % method).ljust(22)
print wrapper.fill(func.figure_name)
示例11: searchPackages
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def searchPackages(self, options, search_str):
candidates = self.search(search_str)
wrapper = TextWrapper(width=80, initial_indent=" ",
subsequent_indent=" ")
# candidates are dictionary of package name - description
for name, desc in candidates.items():
print name
print wrapper.fill(desc)
示例12: _print
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def _print(text):
if VERBOSE:
text_wrapper = TextWrapper(
width=80,
initial_indent=(' ' * 4),
subsequent_indent=(' ' * 8),
)
print text_wrapper.fill(text)
示例13: format_loading_messages_by_lines
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def format_loading_messages_by_lines(errors, warnings):
wrapper = TextWrapper(initial_indent='\t\t', subsequent_indent='\t\t', width=80)
lines = []
if warnings:
lines.append('\t%s' % 'Warnings:')
lines.append('\n\n'.join([wrapper.fill(warning) for warning in warnings]))
if errors:
lines.append('\t%s' % 'Errors:')
lines.append('\n\n'.join([wrapper.fill(error) for error in errors]))
return lines
示例14: help_msg
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def help_msg(err = 0, msg = None):
from os.path import basename
from sys import stderr, argv, exit
from textwrap import fill, TextWrapper
from .utils import get_terminal_width
w = max(get_terminal_width(), 20)
tw = TextWrapper(width = w, subsequent_indent = ' '*18)
if msg != None: print(fill(msg, w), file=stderr)
print("Usage:")
print(tw.fill(" %s input.pts [input2.pts ...] output.pts" % basename(argv[0])))
print("")
print("Optional arguments:")
print(tw.fill(" -h --help Display this help"))
exit(err)
示例15: main
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import fill [as 别名]
def main():
regex = re.compile(r"""
( (?P<comment>((^\#.*)\n?)+) # consecutive comment lines
\n(?P<name>[a-zA-Z0-9._:]+)\s* # variable names
=[\t ]*(?P<value>.*) # variable values
) | ( # OR
\[(?P<section>[a-zA-Z0-9._ :]+)\] # section names
)""", re.VERBOSE | re.MULTILINE)
strip_hash = re.compile("^#", re.MULTILINE)
current_section = ""
keys = {}
for match in regex.finditer(CONFIGURATION_FILE_TEMPLATE):
if match.group("section"):
current_section = match.group('section')
if current_section not in keys:
keys[current_section] = []
continue
comment = re.sub(strip_hash, "", match.group('comment'))
comment = dedent(comment)
keys[current_section].append(
(match.group('name'), match.group('value'), comment)
)
wrapper = TextWrapper(initial_indent = " ",
subsequent_indent = " ")
for section in sorted(keys.keys()):
if not keys[section]:
continue
title = "Section ``%s``" % section
print "%s\n%s\n" % (title, "^"*len(title))
for name, value, comment in keys[section]:
print "``%s``" % name
for para in comment.split("\n\n"):
if para[-1] in string.lowercase:
para = para+"."
print wrapper.fill(para)
print " "
if value:
match = re.match(r"%\(([-a-zA-Z0-9._:]+)\)s$", value)
if match:
value = "same as ``%s``" % match.group(1)
else:
value = "``%s``" % value
print " Default value: %s" % value
print " "