def __init__(self, *args, **kwargs):
drop_whitespace = kwargs.pop('drop_whitespace', True)
textwrap.TextWrapper.__init__(self, *args, **kwargs)
self.drop_whitespace = drop_whitespace
python类TextWrapper()的实例源码
def wrap(text, width=70, **kwargs):
"""
Wrap a single paragraph of text, returning a list of wrapped lines.
"""
if sys.version_info < (2, 6):
return TextWrapper(width=width, **kwargs).wrap(text)
return textwrap.wrap(text, width=width, **kwargs)
# }}}
def show_summaries(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def find_summary(key, key_txt, doc):
return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')]))
str_indent = " " * indent
wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4,
subsequent_indent=str_indent + ' ' * 4)
return cls._show_doc(find_summary, keys=keys, indent=indent,
*args, **kwargs)
def my_wrap(text, width=MAXWIDTH, **kwargs):
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
def printHeader(s, level=1, length=70, prefix='# <XimaExport>:'):
from textwrap import TextWrapper
decs={1: '=', 2: '-', 3: '.'}
indents={1: 0, 2: 4, 3: 8}
dec=decs[level]
ind=indents[level]
indstr=' '*int(ind)
wrapper=TextWrapper()
wrapper.width=length-ind
wrapper.initial_indent=indstr
wrapper.subsequent_indent=indstr
#-------------Get delimiter line-------------
hline='%s%s' %(' '*int(ind),dec*int(length-ind))
#--------------------Wrap texts--------------------
strings=wrapper.wrap('%s %s' %(prefix,s))
#----------------------Print----------------------
try:
print('\n'+hline)
except:
print('\n'+hline.encode('ascii','replace'))
for ss in strings:
try:
print(ss)
except:
print(ss.encode('ascii','replace'))
#print(hline)
return
def printNumHeader(s, idx, num, level=1, length=70, prefix='# <XimaExport>:'):
from textwrap import TextWrapper
decs={1: '=', 2: '-', 3: '.'}
indents={1: 0, 2: 4, 3: 8}
dec=decs[level]
ind=indents[level]
indstr=' '*int(ind)
wrapper=TextWrapper()
wrapper.width=length-ind
wrapper.initial_indent=indstr
wrapper.subsequent_indent=indstr
#-------------Get delimiter line-------------
decl=int((length-ind-2-len(str(idx))-len(str(num)))/2.)
decl=decl*dec
hline1='%s%s %d/%d %s' %(' '*int(ind),decl,idx,num,decl)
#hline2='%s%s' %(' '*int(ind),dec*int(length-ind))
#--------------------Wrap texts--------------------
strings=wrapper.wrap('%s %s' %(prefix,s))
#----------------------Print----------------------
try:
print('\n'+hline1)
except:
print('\n'+hline1.encode('ascii','replace'))
for ss in strings:
try:
print(ss)
except:
print(ss.encode('ascii','replace'))
#print(hline2)
return
def create_file(self):
self.logger.warning("Creating file with methods")
wrapper = TextWrapper()
with open(self.filename, 'w') as output_fileh:
output_fileh.write('Method\n')
output_fileh.write(wrapper.fill(self.methods_paragraph(len(self.trait_samples),len(self.nontrait_samples), self.plasmidtron_version(),self.kmc_version(), self.min_kmers_threshold, self.spades_version(), self.min_contig_length, self.running_time() )))
output_fileh.write('\n\nReferences\n')
output_fileh.write(wrapper.fill(self.references_paragraph()))
def my_wrap(text, width=MAXWIDTH, **kwargs):
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
def _get_wrapper():
global _wrapper
if not _wrapper:
_wrapper = TextWrapper(width=config.get('dzn_width', 70),
subsequent_indent=' '*4, break_long_words=False,
break_on_hyphens = False)
return _wrapper
def build_initialize(self):
"""
Initialize the corpus build.
"""
self.start_time = time.time()
self.logger.info("--- Starting ---")
self.logger.info("Building corpus %s" % self.name)
self.logger.info("Command line arguments: %s" % " ".join(sys.argv[1:]))
if not self._widget:
print("\n%s\n" % textwrap.TextWrapper(width=79).fill(" ".join(self.get_description())))
# Corpus installers may require additional modules. For example,
# Gabra is currently distributed as MongoDB files, which are read by
# using the pymongo library.
# Unless the user wishes to install only the corpus module, try to
# import these additional modules, and raise an exception if they are
# unavailable:
if not self.arguments.only_module:
for module, package, url in self.get_modules():
try:
exec("import {}".format(module))
except ImportError:
raise DependencyError(package, url)
if self.DB.db_type == SQL_MYSQL:
self.DB.connection.execute("SET NAMES 'utf8'")
self.DB.connection.execute("SET CHARACTER SET 'utf8mb4'")
self.DB.connection.execute("SET unique_checks=0")
self.DB.connection.execute("SET foreign_key_checks=0")
def wrap(text, indent=' '):
"""Wrap text to terminal width with default indentation"""
wrapper = textwrap.TextWrapper(
width=int(os.environ.get('COLUMNS', 80)),
initial_indent=indent,
subsequent_indent=indent
)
return '\n'.join(wrapper.wrap(text))
def _packet_parameter(self, parameter, elements):
if isinstance(parameter, model.List):
for p in parameter.parameters:
self._packet_parameter(p, elements)
else:
wrapper = textwrap.TextWrapper()
wrapper.width = 14
text = wrapper.wrap(parameter.name)
texts = []
offset = (40 - self.text_height * len(text)) / 2 - 3
for t in text:
offset += self.text_height
texts.append({
'text': t,
'y': offset,
})
elements.append({
'type': 'element',
'parameterName': texts,
'parameterType': str(parameter.type),
'parameterWidth': parameter.type.width,
'x': self.state.x,
'width': self.box_width,
})
self.state.x += self.box_width
self.state.element_count += 1
if isinstance(parameter, model.Repeater):
self._packet_repeater(parameter, elements)
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))
def formatReply(self):
text = self.comment_text
pgraphs = []
pgraph_accumulator = []
wrap = True
for line in text.split('\n'):
if line.startswith('> '):
wrap = False
line = '> ' + line
if not line:
if pgraph_accumulator:
pgraphs.append((wrap, '\n'.join(pgraph_accumulator)))
pgraph_accumulator = []
wrap = True
continue
pgraph_accumulator.append(line)
if pgraph_accumulator:
pgraphs.append((wrap, '\n'.join(pgraph_accumulator)))
pgraph_accumulator = []
wrap = True
wrapper = textwrap.TextWrapper(initial_indent='> ',
subsequent_indent='> ')
wrapped_pgraphs = []
for wrap, pgraph in pgraphs:
if wrap:
wrapped_pgraphs.append('\n'.join(wrapper.wrap(pgraph)))
else:
wrapped_pgraphs.append(pgraph)
return '\n>\n'.join(wrapped_pgraphs)
def renameConfigFile(config, filename, newNames, dryRun=False, print=print):
wrapper = TextWrapper()
wrapper.width = 80
wrapper.break_long_words = False
wrapper.break_on_hyphens = False
wrap = lambda names: '\n'.join(wrapper.wrap(' '.join(names)))
didRename = False
for propertyName, values in config.items('glyphs'):
glyphNames = values.split()
# print(propertyName, glyphNames)
propChanged = False
for name in glyphNames:
if name in newNames:
sectionChanged = True
if sectionChanged:
config.set('glyphs', propertyName, wrap(glyphNames)+'\n')
didRename = True
# config.set(section, option, value)
if didRename:
s = StringIO()
config.write(s)
s = s.getvalue()
s = re.sub(r'\n(\w+)\s+=\s*', '\n\\1: ', s, flags=re.M)
s = re.sub(r'((?:^|\n)\[[^\]]*\])', '\\1\n', s, flags=re.M)
s = re.sub(r'\n\t\n', '\n\n', s, flags=re.M)
s = s.strip() + '\n'
print('Writing', filename)
if not dryRun:
with open(filename, 'w') as f:
f.write(s)
def updateConfigFile(config, filename, rmnames):
wrapper = TextWrapper()
wrapper.width = 80
wrapper.break_long_words = False
wrapper.break_on_hyphens = False
wrap = lambda names: '\n'.join(wrapper.wrap(' '.join(names)))
didChange = False
for propertyName, values in config.items('glyphs'):
glyphNames = values.split()
propChanged = False
glyphNames2 = [name for name in glyphNames if name not in rmnames]
if len(glyphNames2) < len(glyphNames):
print('[fontbuild.cfg] updating glyphs property', propertyName)
config.set('glyphs', propertyName, wrap(glyphNames2)+'\n')
didChange = True
if didChange:
s = StringIO()
config.write(s)
s = s.getvalue()
s = re.sub(r'\n(\w+)\s+=\s*', '\n\\1: ', s, flags=re.M)
s = re.sub(r'((?:^|\n)\[[^\]]*\])', '\\1\n', s, flags=re.M)
s = re.sub(r'\n\t\n', '\n\n', s, flags=re.M)
s = s.strip() + '\n'
print('Writing', filename)
if not dryRun:
with open(filename, 'w') as f:
f.write(s)
def __get_text_wrapper(width=60):
"""
Get text wrapper with a fixed with.
:param width: width of the wrapper. Default 60.
:return: text wrapper
:rtype: :py:class:`TextWrapper`
"""
wrapper = TextWrapper()
wrapper.width = width
wrapper.subsequent_indent = " "
return wrapper
def dump_recursive_parents(rpc,
post_author,
post_permlink,
limit=1,
format="markdown"):
global currentThreadDepth
limit = int(limit)
postWrapper = TextWrapper()
postWrapper.width = 120
postWrapper.initial_indent = " " * (limit)
postWrapper.subsequent_indent = " " * (limit)
if limit > currentThreadDepth:
currentThreadDepth = limit + 1
post = rpc.get_content(post_author, post_permlink)
if limit and post["parent_author"]:
parent = rpc.get_content_replies(post["parent_author"], post["parent_permlink"])
if len(parent):
dump_recursive_parents(rpc, post["parent_author"], post["parent_permlink"], limit - 1)
meta = {}
for key in ["author", "permlink"]:
meta[key] = post[key]
meta["reply"] = "@{author}/{permlink}".format(**post)
if format == "markdown":
body = markdownify(post["body"])
else:
body = post["body"]
yaml = frontmatter.Post(body, **meta)
print(frontmatter.dumps(yaml))
def dump_recursive_comments(rpc,
post_author,
post_permlink,
depth=0,
format="markdown"):
global currentThreadDepth
postWrapper = TextWrapper()
postWrapper.width = 120
postWrapper.initial_indent = " " * (depth + currentThreadDepth)
postWrapper.subsequent_indent = " " * (depth + currentThreadDepth)
depth = int(depth)
posts = rpc.get_content_replies(post_author, post_permlink)
for post in posts:
meta = {}
for key in ["author", "permlink"]:
meta[key] = post[key]
meta["reply"] = "@{author}/{permlink}".format(**post)
if format == "markdown":
body = markdownify(post["body"])
else:
body = post["body"]
yaml = frontmatter.Post(body, **meta)
print(frontmatter.dumps(yaml))
reply = rpc.get_content_replies(post["author"], post["permlink"])
if len(reply):
dump_recursive_comments(rpc, post["author"], post["permlink"], depth + 1)
def setUp(self):
self.wrapper = TextWrapper(width=45)