本文整理汇总了Python中textwrap.TextWrapper.wrap方法的典型用法代码示例。如果您正苦于以下问题:Python TextWrapper.wrap方法的具体用法?Python TextWrapper.wrap怎么用?Python TextWrapper.wrap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textwrap.TextWrapper
的用法示例。
在下文中一共展示了TextWrapper.wrap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestResult
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
class TestResult(object):
def __init__(self, name, url, group, deprecates, text, check_type,
result, output_extra, attachments=[]):
self.name = name
self.url = url
self.group = group
self.deprecates = deprecates
self.text = re.sub("\s+", " ", text) if text else ''
self.type = check_type
self.result = result
self.output_extra = output_extra
self.attachments = attachments
if self.output_extra:
self.output_extra = re.sub("\s+", " ", self.output_extra)
self.wrapper = TextWrapper(width=78, subsequent_indent=" " * 5,
break_long_words=False, )
def get_text(self):
strbuf = StringIO.StringIO()
main_lines = self.wrapper.wrap("%s: %s %s" %
(TEST_STATES[self.result],
self.type,
self.text))
strbuf.write("%s" % '\n'.join(main_lines))
if self.output_extra and self.output_extra != "":
strbuf.write("\n")
extra_lines = self.wrapper.wrap(" Note: %s" %
self.output_extra)
strbuf.write('\n'.join(extra_lines))
return strbuf.getvalue()
示例2: dict_str
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def dict_str(self):
"""Build a human-readable definition for this word, including data for each synset"""
tw = TextWrapper(width=self.LINE_WIDTH_MAX,
initial_indent=(self.prefix_fmtf_line_first % self.category_map_rev[self.category]),
subsequent_indent=(self.prefix_fmtn_line_first % (len(self.category_map_rev[self.category]), '')))
lines = (tw.wrap(self.synsets[0].synset_get().dict_str()))
i = 2
prefix_fmtn_line_nonfirst = self.prefix_fmtn_line_nonfirst
pfln_len = 0
for ss_wrap in self.synsets[1:]:
# adjust indenting based on index-number with
pfln_len_new = len('%d' % (i,))
if (pfln_len_new > pfln_len):
pfln_len = pfln_len_new
pfln_str = (self.prefix_fmtn_line_nonfirst % (pfln_len, ''))
# format data for this synset
synset = ss_wrap.synset_get()
tw = TextWrapper(width=self.LINE_WIDTH_MAX,
initial_indent=(self.prefix_fmtf_line_nonfirst % i),
subsequent_indent=pfln_str)
lines.extend(tw.wrap(synset.dict_str()))
i += 1
return self.linesep.join(lines)
示例3: __str__
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def __str__(self):
if self.networks and len(self.networks) > 1:
lines = ["Nexus dataset '%s' (#%s) with %d networks" % \
(self.sid, self.id, len(self.networks))]
else:
lines = ["Nexus dataset '%(sid)s' (#%(id)s)" % self.__dict__]
lines.append("vertices/edges: %s" % self.vertices_edges)
if self.name:
lines.append("name: %s" % self.name)
if self.tags:
lines.append("tags: %s" % "; ".join(self.tags))
if self.rest:
wrapper = TextWrapper(width=76, subsequent_indent=' ')
keys = sorted(self.rest.iterkeys())
if "attribute" in self.rest:
keys.remove("attribute")
keys.append("attribute")
for key in keys:
for value in self.rest.getlist(key):
paragraphs = str(value).splitlines()
wrapper.initial_indent = "%s: " % key
for paragraph in paragraphs:
ls = wrapper.wrap(paragraph)
if ls:
lines.extend(wrapper.wrap(paragraph))
else:
lines.append(" .")
wrapper.initial_indent = " "
return "\n".join(lines)
示例4: TestResult
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
class TestResult(object):
nowrap = ["CheckRpmLint", "CheckSourceMD5"]
def __init__(self, name, url, group, deprecates, text, check_type,
result, output_extra):
self.name = name
self.url = url
self.group = group
self.deprecates = deprecates
self.text = re.sub("\s+", " ", text)
self.type = check_type
self.result = result
self.output_extra = output_extra
if self.output_extra and self.name not in TestResult.nowrap:
self.output_extra = re.sub("\s+", " ", self.output_extra)
self.wrapper = TextWrapper(width=78, subsequent_indent=" " * 5,
break_long_words=False, )
def get_text(self):
strbuf = StringIO.StringIO()
main_lines = self.wrapper.wrap("%s: %s %s" %
(TEST_STATES[self.result],
self.type,
self.text))
strbuf.write("%s" % '\n'.join(main_lines))
if self.output_extra and self.output_extra != "":
strbuf.write("\n")
if self.name in TestResult.nowrap:
strbuf.write(self.output_extra)
else:
extra_lines = self.wrapper.wrap(" Note: %s" %
self.output_extra)
strbuf.write('\n'.join(extra_lines))
return strbuf.getvalue()
示例5: create_verification_message
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def create_verification_message(userInfo, siteInfo, toAddr, fromAddr,
verificationId):
container = MIMEMultipart('alternative')
subject = u'Verify your email address on %s' % siteInfo.name
container['Subject'] = str(Header(subject.encode(utf8), utf8))
container['From'] = str(fromAddr)
container['To'] = str(toAddr)
wrapper = TextWrapper(width=72)
b = 'We received a request to add the email address <%s> '\
'to your profile on %s. To verify that you control this '\
'email address, please click the following link.' % \
(toAddr, siteInfo.name)
body = '\n'.join(wrapper.wrap(b))
u = '%s/r/verify/%s' % (siteInfo.url, verificationId)
d = {
'siteName': siteInfo.name,
'siteUrl': siteInfo.url,
'body': body,
'verificationUrl': u
}
t = u'''Hi there!
%(body)s
%(verificationUrl)s
--
%(siteName)s
%(siteUrl)s
''' % d
text = MIMEText(t.strip().encode(utf8), 'plain', utf8)
container.attach(text)
hb = 'We received a request to add the email address '\
'<a href="mailto:%s">%s</a> '\
'to your profile on %s. To verify that you control this '\
'email address, please click the following link.' % \
(toAddr, toAddr, siteInfo.name)
hbody = '\n'.join(wrapper.wrap(hb))
d['hbody'] = hbody
h = u'''<p><strong>Hi there!</strong></p>
<p>%(hbody)s</p>
<pre>
<a href="%(verificationUrl)s">%(verificationUrl)s</a>
</pre>
<hr/>
<p><a href="%(siteUrl)s">%(siteName)s</a></p>
''' % d
html = MIMEText(h.encode(utf8), 'html', utf8)
container.attach(html)
retval = container.as_string()
assert retval
assert type(retval) == str
return retval
示例6: TestResult
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
class TestResult(object):
''' The printable outcome of a test, stored in check.result. '''
TEST_STATES = {
'pending': '[ ]', 'pass': '[x]', 'fail': '[!]', 'na': '[-]'}
def __init__(self, check, result, output_extra, attachments=None):
self.check = check
self.text = re.sub(r"\s+", " ", check.text) if check.text else ''
self.result = result
self._leader = self.TEST_STATES[result] + ': '
self.output_extra = output_extra
self.attachments = attachments if attachments else []
if self.output_extra:
self.output_extra = re.sub(r"\s+", " ", self.output_extra)
self.set_indent(5)
url = property(lambda self: self.check.url)
name = property(lambda self: self.check.name)
type = property(lambda self: self.check.type)
group = property(lambda self: self.check.group)
deprecates = property(lambda self: self.check.deprecates)
is_failed = property(lambda self: self.check.is_failed)
state = property(lambda self: self.result)
def set_indent(self, indent):
''' Set indentation level for get_text (int, defaults to 5). '''
# pylint: disable=W0201
self.wrapper = TextWrapper(width = 78,
subsequent_indent = " " * indent,
break_long_words = False, )
def set_leader(self, leader):
''' Set the leading string, defaults to [!], [ ], [-], etc. '''
self._leader = leader
def get_text(self):
''' Return printable representation of test. '''
strbuf = StringIO.StringIO()
main_lines = self.wrapper.wrap(self._leader + self.text)
strbuf.write('\n'.join(main_lines))
if self.output_extra and self.output_extra != "":
strbuf.write("\n")
extra_lines = self.wrapper.wrap(
self.wrapper.subsequent_indent +
"Note: " + self.output_extra)
strbuf.write('\n'.join(extra_lines))
if self.is_failed:
see = self.wrapper.wrap(
self.wrapper.subsequent_indent +
"See: " + self.url)
strbuf.write("\n" + "\n".join(see))
return strbuf.getvalue()
def __str__(self):
self.get_text()
示例7: dict_str
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def dict_str(self):
tw = TextWrapper(width=self.LINE_WIDTH_MAX,
initial_indent=(self.prefix_fmtf_line_first % self.category_map_rev[self.category]),
subsequent_indent=self.prefix_fmtn_line_first)
lines = (tw.wrap(self.synsets[0].dict_str()))
i = 2
for synset in self.synsets[1:]:
tw = TextWrapper(width=self.LINE_WIDTH_MAX,
initial_indent=(self.prefix_fmtf_line_nonfirst % i),
subsequent_indent=self.prefix_fmtn_line_nonfirst)
lines.extend(tw.wrap(synset.dict_str()))
i += 1
return self.linesep.join(lines)
示例8: format_search_result
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def format_search_result(number, result):
term_width = terminal_size()[0]
if term_width > 8:
term_width = term_width - 8
wrapper = TextWrapper(initial_indent=" ", subsequent_indent=" ", width=term_width)
heading = "%s) %s " % (number, result['name'])
if 'categories' in result and result['categories']:
heading += "[%s] " % (", ".join(result['categories']),)
if 'authors' in result and result['authors']:
heading += "(author: %s) " % (", ".join(result['authors']),)
right = ""
if 'last_updated' in result:
right += " Updated %s" % (result['last_updated'])
if 'stage' in result:
right += " [%s]" % (result['stage'],)
heading += right.rjust(term_width - len(heading))
lines = [heading, '']
if 'summary' in result and result['summary']:
lines += wrapper.wrap(result['summary'])
lines.append('')
return lines
示例9: text
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def text(self, text, offset=None, horiz=None, vert=None, *,
angle=None, font=None, colour=None, width=None):
attrs = dict()
style = list()
transform = list()
if vert is not None:
baselines = {
self.CENTRE: "central",
self.TOP: "text-before-edge",
self.BOTTOM: "text-after-edge",
}
style.append(("dominant-baseline", baselines[vert]))
if horiz is not None:
anchors = {
self.CENTRE: "middle",
self.LEFT: "start",
self.RIGHT: "end",
}
style.append(("text-anchor", anchors[horiz]))
transform.extend(self._offset(offset))
if angle is not None:
transform.append("rotate({})".format(angle * self.flip[1]))
if font is not None:
attrs["class"] = font
attrs.update(self._colour(colour))
with self.element("text", attrs, style=style, transform=transform):
if width is None:
if isinstance(text, str):
self.xml.characters(text)
else:
for seg in text:
attrs = dict()
if seg.get("overline"):
attrs["text-decoration"] = "overline"
self.tree(("tspan", attrs, (seg["text"],)))
return
# Very hacky approximation of the size of each character
# as one en wide
width /= self.textsize / 2
wrapper = TextWrapper(width=width, replace_whitespace=False)
hardlines = text.splitlines(keepends=True)
if not hardlines:
hardlines.append("")
line = 0
for hardline in hardlines:
wrapped = wrapper.wrap(hardline)
if not wrapped: # Caused by empty string
wrapped.append("")
for softline in wrapped:
lineattrs = {
"x": "0",
"y": "{}em".format(line / 0.875),
"xml:space": "preserve",
}
self.tree(("tspan", lineattrs, (softline,)))
line += 1
示例10: sections_by_subject
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def sections_by_subject(args, store):
courses = store.get_courses(
term=args.term,
subject=args.subject,
)
pad = 2
wrapper = TextWrapper(
initial_indent=' ' * pad,
subsequent_indent=' ' * (4 + pad),
)
for course in courses:
course = Course(args.subject, course['number'])
sections = store.get_sections(
course=course,
term=args.term,
)
if len(sections) != 0:
print(course.get_number() + '\n'.join(
wrapper.wrap(' '.join([
section['name'] for section in sections
]))
))
print('')
示例11: info
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def info(cls, _str=True):
if not _str:
return PCFGConfig.argNames
# Auto text wrapper to output the doc.
tw = TextWrapper()
tw.initial_indent = " "
tw.subsequent_indent = " "
retVal = "General Configuration: \n"
for argName in PCFGConfig.argNames:
arg = str(argName["arg"])
argreq = str(argName["req"])
argtype = str(argName["type"].__name__)
argdef = str(argName["def"])
argdoc = str(argName["doc"])
argex = str(argName["ex"])
doclines = tw.wrap(argdoc)
aType = "optional"
if argreq:
aType = "required"
retVal += " %s (%s, %s):\n" % (arg, argtype, aType)
retVal += " Defaults to %s\n" % (argdef)
for docline in doclines:
retVal += "%s\n" % docline
retVal += " Example: %s\n" % argex
retVal += "\n"
return retVal
示例12: courses
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def courses(args, store):
if args.subject is None:
err('--subject is required')
else:
if args.chatty:
print('Subject: %s\n' % unicode(args.subject))
courses = store.get_courses(
term=args.term,
subject=args.subject,
)
if courses is None:
not_available()
else:
pad = 2
wrapper = TextWrapper(
initial_indent=' ' * (4 + pad),
subsequent_indent=' ' * (4 + pad),
)
for course in courses:
print((' ' * pad).join((
course['number'],
course['name'],
)))
print('')
d = course['description']
if d is not None:
for line in wrapper.wrap(d):
print(line)
print('')
示例13: wrap_for_make
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def wrap_for_make(items):
line = join(sorted(items))
wrapper = TextWrapper()
wrapper.width = 60
wrapper.break_on_hyphens = False
wrapper.subsequent_indent = '\t' * 2
return ' \\\n'.join(wrapper.wrap(line))
示例14: msg
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def msg(text, sep=' ', *args, **kwargs):
'''
A convenience to neatly format message strings, such as error messages.
'''
text_wrapper = TextWrapper(*args, **kwargs)
return sep.join(text_wrapper.wrap(text.strip()))
示例15: wrap
# 需要导入模块: from textwrap import TextWrapper [as 别名]
# 或者: from textwrap.TextWrapper import wrap [as 别名]
def wrap(payload):
indent = ' '
tw = TextWrapper(
width=70,
initial_indent=indent,
subsequent_indent=indent)
return u'\n'.join(tw.wrap(payload))