當前位置: 首頁>>代碼示例>>Python>>正文


Python textwrap.shorten方法代碼示例

本文整理匯總了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
        ) 
開發者ID:python-discord,項目名稱:bot,代碼行數:21,代碼來源:test_infractions.py

示例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)) 
開發者ID:buckket,項目名稱:twtxt,代碼行數:22,代碼來源:helper.py

示例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() 
開發者ID:mingrammer,項目名稱:awesome-finder,代碼行數:22,代碼來源:tui.py

示例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 
開發者ID:saezlab,項目名稱:pypath,代碼行數:21,代碼來源:common.py

示例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",
    } 
開發者ID:kiwicom,項目名稱:gitlab-unfurly,代碼行數:24,代碼來源:unfurl_message.py

示例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!') 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:22,代碼來源:rnx2crnx.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:24,代碼來源:qualitycheck.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:27,代碼來源:renamesite.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:26,代碼來源:up2lower.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:23,代碼來源:orderfile.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:26,代碼來源:low2upper.py

示例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 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:25,代碼來源:unificate.py

示例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!') 
開發者ID:purpleskyfall,項目名稱:pinot,代碼行數:22,代碼來源:crnx2rnx.py

示例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}" 
開發者ID:storybro,項目名稱:storybro,代碼行數:21,代碼來源:player.py

示例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
        ) 
開發者ID:python-discord,項目名稱:bot,代碼行數:15,代碼來源:test_infractions.py


注:本文中的textwrap.shorten方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。