本文整理汇总了Python中textwrap.shorten方法的典型用法代码示例。如果您正苦于以下问题:Python textwrap.shorten方法的具体用法?Python textwrap.shorten怎么用?Python textwrap.shorten使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textwrap
的用法示例。
在下文中一共展示了textwrap.shorten方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_apply_ban_reason_truncation
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def test_apply_ban_reason_truncation(self, post_infraction_mock, get_active_mock):
"""Should truncate reason for `ctx.guild.ban`."""
get_active_mock.return_value = None
post_infraction_mock.return_value = {"foo": "bar"}
self.cog.apply_infraction = AsyncMock()
self.bot.get_cog.return_value = AsyncMock()
self.cog.mod_log.ignore = Mock()
self.ctx.guild.ban = Mock()
await self.cog.apply_ban(self.ctx, self.target, "foo bar" * 3000)
self.ctx.guild.ban.assert_called_once_with(
self.target,
reason=textwrap.shorten("foo bar" * 3000, 512, placeholder="..."),
delete_message_days=0
)
self.cog.apply_infraction.assert_awaited_once_with(
self.ctx, {"foo": "bar"}, self.target, self.ctx.guild.ban.return_value
)
示例2: style_tweet
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def style_tweet(tweet, porcelain=False):
conf = click.get_current_context().obj["conf"]
limit = conf.character_limit
if porcelain:
return "{nick}\t{url}\t{tweet}".format(
nick=tweet.source.nick,
url=tweet.source.url,
tweet=str(tweet))
else:
if sys.stdout.isatty() and not tweet.text.isprintable():
return None
styled_text = format_mentions(tweet.text)
len_styling = len(styled_text) - len(click.unstyle(styled_text))
final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime
return "➤ {nick} ({time}):\n{tweet}".format(
nick=click.style(tweet.source.nick, bold=True),
tweet=final_text,
time=click.style(timestamp, dim=True))
示例3: display
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def display(self):
"""Display the found awesome content on result window"""
self.result_window.erase()
for idx, val in enumerate(self.matched_blocks[self.top:self.top + self.max_lines]):
if val['type'] == 'category':
# Highlight the current cursor line
if idx == self.current:
self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'),
curses.color_pair(2))
else:
self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'),
curses.color_pair(1))
elif val['type'] == 'awesome':
# Highlight the current cursor line
if idx == self.current:
self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...'),
curses.color_pair(2))
else:
self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...'))
self.result_window.refresh()
示例4: wrap_truncate
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def wrap_truncate(text, width = None, maxlen = None):
if isinstance(text, list_like):
text = ', '.join(text)
if not isinstance(text, basestring):
text = str(text)
if maxlen:
text = textwrap.shorten(text, width = maxlen)
if width:
text = textwrap.wrap(text, width = width)
return os.linesep.join(text) if isinstance(text, list_like) else text
示例5: get_note_merge_requests_info
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def get_note_merge_requests_info(session, path_info):
api_path = f"/api/v4/projects/{path_info.quoted_id}/merge_requests/{path_info.identifier}/notes/{path_info.note}"
data = get_data_from_api(session, api_path)
mr_data = get_merge_request_data(session, path_info)
try:
mr_title = mr_data["title"].strip()
mr_state = mr_data["state"]
body = data["body"]
except IndexError as e:
log.exception(f"Err in data from GL: {e}")
raise
return {
"author_name": format_user(data["author"]),
"author_link": data["author"]["web_url"],
"author_icon": data["author"]["avatar_url"],
"title": f"Comment on merge request: {mr_title}",
"text": textwrap.shorten(body.strip(), width=300, placeholder="…"),
"color": MR_STATE_COLORS[mr_state],
"ts": arrow.get(data["created_at"]).timestamp,
"footer": "Merge Request Note",
}
示例6: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir = args.files, args.out
keep_src, recursive = args.keep, args.recursive
# create output directory
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
# make input args for rnx2crx function
conv_args = ((src, out_dir, keep_src) for src in itertools.chain(*globs))
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
if not keep_src:
print('Delete source files when complete')
# start parallel task, get a file name list of convert failed.
failed = parallel_run(rnx2crx, conv_args)
if failed:
print('\nConvert failed filename: {}'.format(', '.join(failed)))
else:
print('\nAll convert tasks are finished!')
示例7: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_fmt, recursive = args.files, args.out, args.recursive
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
src_files = [src for src in itertools.chain(*globs)]
# make input args for teqc function
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
# if output format is table, print a table header first
if out_fmt == 'table' or out_fmt == 't':
header = ('file', 'date', 'start', 'end', 'hours', 'percent',
'SN1', 'SN2', 'MP1', 'MP2', 'CSR')
style = ('\n{0: ^14s} {1: ^12s} {2: ^14s} {3: ^14s} {4: >6s} {5: >7s}'
'{6: >6s} {7: >6s} {8: >6s} {9: >5s} {10: >5s}')
print(style.format(*header))
# start parallel processing
failed = parallel_teqc(src_files, args.nav, out_fmt)
if failed:
print('\nQuality check failed files: {}'.format(', '.join(failed)))
return 0
示例8: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir, sitemap = args.files, args.out, yaml.load(args.cfg)
keep_src, recursive = args.keep, args.recursive
# make output directory if out_dir is set
if out_dir is not None:
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
# start process
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
if not keep_src:
print('Delete source files when complete')
missing = set()
for src_file in itertools.chain(*globs):
res = rename_site(src_file, out_dir, sitemap, keep_src)
# if return is not None, means site not found in sitemap
if res is not None:
missing.add(res)
if missing:
print('Sites not found in sitemap: {}'.format(', '.join(missing)))
return 0
示例9: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir = args.files, args.out
keep_src, recursive = args.keep, args.recursive
# if the out_dir is None and --keep is setted, process as an error
if keep_src and out_dir is None:
err_message = 'Error! Blank output directory is conflict with --keep.'
print(err_message, file=sys.stderr)
return 1
# start process
if out_dir is not None:
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
count = 0
for src_file in itertools.chain(*globs):
up2lower(src_file, out_dir, keep_src)
count += 1
print('{} files have been processed.'.format(count))
return 0
示例10: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir = args.files, args.out
keep_src, recursive = args.keep, args.recursive
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
# start process
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
if not keep_src:
print('Delete source files when complete')
for src_file in itertools.chain(*globs):
dst_dir = os.path.join(out_dir, which_dir(src_file))
os.makedirs(dst_dir, exist_ok=True)
print('{} => {}'.format(src_file, dst_dir))
if keep_src:
shutil.copy2(src_file, dst_dir)
else:
shutil.move(src_file, dst_dir)
return 0
示例11: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir = args.files, args.out
keep_src, recursive = args.keep, args.recursive
# if the out_dir is None and --keep is setted, process as an error
if keep_src and out_dir is None:
err_message = 'Error! Blank output directory is conflict with --keep.'
print(err_message, file=sys.stderr)
return 1
# start process
if out_dir is not None:
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
count = 0
for src_file in itertools.chain(*globs):
low2upper(src_file, out_dir, keep_src)
count += 1
print('{} files have been processed.'.format(count))
return 0
示例12: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function"""
args = init_args()
globstrs, out_dir, infos = args.files, args.out, yaml.load(args.cfg)
keep_src, recursive = args.keep, args.recursive
# create output directory
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
files = itertools.chain(*globs)
# make input args for teqc function
teqc_args = ((src, make_args(src, infos), out_dir, keep_src) for src in files)
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
if not keep_src:
print('Delete source files when complete')
# start parallel task, get a filename list of unificate failed.
failed = parallel_run(teqc, teqc_args)
if failed:
print('\nUnificate failed filename: {}'.format(', '.join(failed)))
else:
print('\nAll unificate tasks are finished!')
return 0
示例13: main
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def main():
"""Main function."""
args = init_args()
globstrs, out_dir = args.files, args.out
keep_src, recursive = args.keep, args.recursive
# create output directory
os.makedirs(out_dir, exist_ok=True)
# collect input globstrs into a glob list
globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
# make input args for crx2rnx function
conv_args = ((src, out_dir, keep_src) for src in itertools.chain(*globs))
print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
if not keep_src:
print('Delete source files when complete')
# start parallel task, get a file name list of convert failed.
failed = parallel_run(crx2rnx, conv_args)
if failed:
print('\nConvert failed filename: {}'.format(', '.join(failed)))
else:
print('\nAll convert tasks are finished!')
示例14: format_block_for_list
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def format_block_for_list(self, block, index, index_width):
if block.attrs.get('type') == 'input':
icon = self.settings.icon_for_input
else:
icon = self.settings.icon_for_output
if block.attrs.get('pinned'):
pin = self.settings.icon_for_pins
else:
pin = " "
index_label = str(index).rjust(index_width)
text = block.text
if self.settings.fill_width:
text = textwrap.shorten(text, self.settings.fill_width, placeholder="")
return f"{icon}{pin} {index_label}: {text}"
示例15: test_apply_kick_reason_truncation
# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import shorten [as 别名]
def test_apply_kick_reason_truncation(self, post_infraction_mock):
"""Should truncate reason for `Member.kick`."""
post_infraction_mock.return_value = {"foo": "bar"}
self.cog.apply_infraction = AsyncMock()
self.cog.mod_log.ignore = Mock()
self.target.kick = Mock()
await self.cog.apply_kick(self.ctx, self.target, "foo bar" * 3000)
self.target.kick.assert_called_once_with(reason=textwrap.shorten("foo bar" * 3000, 512, placeholder="..."))
self.cog.apply_infraction.assert_awaited_once_with(
self.ctx, {"foo": "bar"}, self.target, self.target.kick.return_value
)