当前位置: 首页>>代码示例>>Python>>正文


Python textwrap.shorten函数代码示例

本文整理汇总了Python中textwrap.shorten函数的典型用法代码示例。如果您正苦于以下问题:Python shorten函数的具体用法?Python shorten怎么用?Python shorten使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了shorten函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _write_test_status

 def _write_test_status(self,
                        test_repr: str,
                        location: tp.Tuple[str, int, str],
                        with_progress: bool = False,
                        rewrite: bool = False,
                        newline: bool = False,
                        **markup):
     w = self._tw.fullwidth
     loc = location[2].replace('.', '::')
     if len(loc) > w // 2 - 8:
         loc = textwrap.shorten(loc, w // 2 - 8)
     right = loc + ' [100%]'
     l_left = len(test_repr)
     l_right = len(right) + 1
     if l_left + l_right >= w:
         test_repr = textwrap.shorten(test_repr, w - l_right - 1)
         l_left = len(test_repr)
     if rewrite:
         self.write('\r')
     self.write(test_repr, **markup)
     self.write(' ' * (w - l_left - l_right) + loc, light=True)
     if with_progress:
         self.write(self._get_progress_information_message(), cyan=True)
     else:
         self.write(' [ ~ %]', cyan=True)
     if newline:
         self.write_line('')
开发者ID:Scalr,项目名称:revizor-tests,代码行数:27,代码来源:reporter.py

示例2: _display

    def _display(self, correct, answer, answers=None):
        self._message_window.refresh()
        self._message_window.border()

        text_width = self._width - 2
        text_height = self._height - 2

        self._message_window.refresh()

        if correct:
            self._message_window.addstr(1, int((text_width - 8)/2), "CORRECT!")
        else:
            self._message_window.addstr(1, int((text_width - 6)/2), "WRONG!")


            if self._show_answers_on_fail:
                self._answers_window.clear()
                self._answers_window.border()
                self._answers_window.addstr(0, 1, "[Accepted answers]")

                max_answers = self._answers_height - 2
                display_all_answers = len(answers) <= max_answers
                displayed_answers = answers if display_all_answers else answers[0:max_answers]

                if not display_all_answers:
                    self._answers_window.addstr(self._answers_height - 1, self._width - 7, "[...]")

                for index, answer in enumerate(displayed_answers):
                    self._answers_window.addstr(index + 1, 1, textwrap.shorten(answer, text_width, placeholder = "..."))

                self._answers_window.refresh()
开发者ID:kondziu,项目名称:6p,代码行数:31,代码来源:cli.py

示例3: sendChatPushNotification

def sendChatPushNotification(user, message):
	device = FCMDevice.objects.filter(user = user, active = True).first()

	if not device is None:
		serializer = ChatSerializer(message)

		json_r = json.dumps(serializer.data)
		json_r = json.loads(json_r)
		
		info = {}

		info["data"] = {}
		info["data"]["messages"] = []
		info["data"]["message_sent"] = json_r

		info["message"] = ""
		info["type"] = ""
		info["title"] = ""
		info["success"] = True
		info["number"] = 1
		info['extra'] = 0

		response = json.dumps(info)

		title = str(message.user).join(_(" sent a message"))

		simple_notify = textwrap.shorten(strip_tags(message.text), width = 30, placeholder = "...")

		if message.image:
			simple_notify += " ".join(_("[Photo]"))

		device.send_message(title = str(message.user), body = simple_notify, data = {"response": response, "title": title, "body": simple_notify, "user_from": message.user.email, "user_name": str(message.user), "user_img": message.user.image_url, "type": 'chat', "click_action": 'FLUTTER_NOTIFICATION_CLICK'})
开发者ID:amadeusproject,项目名称:amadeuslms,代码行数:32,代码来源:utils.py

示例4: pack_table

 def pack_table(info):
     return '<table>\n' + "\n".join(
         '<tr><td align="right" width="90">{}:</td>\n'
         '<td width="40">{}</td></tr>\n'.format(
             d,
             textwrap.shorten(str(v), width=30, placeholder="..."))
         for d, v in info
     ) + "</table>\n"
开发者ID:PrimozGodec,项目名称:orange3,代码行数:8,代码来源:owdatainfo.py

示例5: main

def main():
    url = 'http://feed.exileed.com/vk/feed/pynsk'

    _section_title = 'Колонка автора'
    _res_title = 'Александр Сапронов (PyNSK)'

    resource = Resource.objects.filter(title=_res_title)
    assert resource.count() == 1, "Not found resoure: %s" % _res_title
    resource = resource[0]

    section = Section.objects.filter(title=_section_title)
    assert section.count() == 1, "Not found section: %s" % _section_title
    section = section[0]

    r = re.compile(r"(htt(p|ps)://[^ ]+)")

    today = datetime.date.today()
    week_before = today - datetime.timedelta(weeks=1)
    rssnews = feedparser.parse(url)
    for n in reversed(rssnews.entries):
        if len(Item.objects.filter(link=n.link)[0:1]):
            continue

        # print("Parse: %s" % n.link)
        title = None
        content = None

        time_struct = getattr(n, 'published_parsed', None)
        if time_struct:
            _timestamp = mktime(time_struct)
            dt = datetime.datetime.fromtimestamp(_timestamp)
            if dt.date() < week_before:
                continue

        text = n.summary
        for x in l:
            if x in text and '<br><br>' in text.split(x)[1]:
                _ = text.split(x)[1].split('<br>')
                title = x + _[0]
                content = ' </br>\n'.join(filter(lambda x: x, _[1:]))

                content = r.sub(r'<a href="\1">\1</a>', content)
                break

        if title is not None and content is not None:
            content_link = "<a href='%s' target='_blank'>[Продолжение]</a>" % n.link
            content = textwrap.shorten(content, width=300, placeholder="...%s" % content_link)\
                .replace('<a...', '...')
            _ = {
                'link': n.link,
                'description': content,
                'title': title,
                'resource': resource,
                'language': 'ru',
                'section': section,
                'status': 'active',
            }
            save_item(_)
开发者ID:cheshirski,项目名称:pythondigest,代码行数:58,代码来源:parser_vk_pynsk.py

示例6: print_content_entry

def print_content_entry(entry, index = 1):
    assert(isinstance(entry, dict))
    name = entry.pop('name')
    xtype = entry.pop('type')
    print("Name: {} {}".format(name, xtype))
    for k in sorted(entry.keys()):
        value = entry[k]
        if isinstance(value, str):
            value = textwrap.shorten(value, 60)
        print("    {}: {}".format(k, value))
开发者ID:ColgateUniversityComputerScience,项目名称:csscreen,代码行数:10,代码来源:screenclient.py

示例7: list_commands

def list_commands():
    """ List all commands """
    text = ""
    for n in sorted(Env.COMMANDS):
        c = Env.COMMANDS[n]
        d = c.doc
        a = c.arg_parser
        doc = textwrap.shorten(d,60)
        doc = "%- 20s %s %s\n" % (n, doc, a)
        text += doc
    Env.show(text)
开发者ID:wonkodv,项目名称:hanstool,代码行数:11,代码来源:helpers.py

示例8: __enter__

 def __enter__(self):
     if self._use_timer:
         self._enter_time = time()
     self._curr_ticks = 0
     self._next_threshold = 0
     # reserving space for percentage
     space = self._lineman.use_width - 4
     line = shorten(self._description, width = space, placeholder = '...')
     line += wrap_color(2, '.' * (space - len(line)))
     self._prefix = line
     self._push_label(wrap_color(3, '  0%'))
     return self
开发者ID:sergeev917,项目名称:cve,代码行数:12,代码来源:Console.py

示例9: string

    def string(self):
        properties = self._current['properties']

        headline = ' '.join(properties['parameters']['NWSheadline'])
        start = dateutil.parser.parse(properties['effective'])
        end = dateutil.parser.parse(properties['expires'])
        return '{} [ {}({}): FROM {} TO {} -- {} ]'.format(
                self.location.name,
                properties['event'],
                properties['severity'],
                start.strftime('%b %d %X'),
                end.strftime('%b %d %X'),
                textwrap.shorten(headline, width=200))
开发者ID:kyleterry,项目名称:tenyks-contrib,代码行数:13,代码来源:weather.py

示例10: style_tweet

def style_tweet(tweet, porcelain=False):
    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(
            nick=tweet.source.nick,
            url=tweet.source.url,
            tweet=str(tweet))
    else:
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True),
            tweet=textwrap.shorten(styled_text, 140 + len_styling),
            time=click.style(tweet.relative_datetime, dim=True))
开发者ID:texttheater,项目名称:twtxt,代码行数:13,代码来源:helper.py

示例11: notify_user_about_clarification

def notify_user_about_clarification(request, clarification):
    messages.add_message(
        request,
        msg_lvl.INFO_PERSISTENT,
        'На Ваш вопрос был <a href="{}" data-clarification="{}">дан ответ</a>: "{}"'.format(
            clarification.get_absolute_url(),
            clarification.id,
            html.escape(
                textwrap.shorten(html.strip_tags(clarification.answer_html), 70, placeholder='...')
            ),
        ),
        extra_tags='safe',
        user=clarification.user,
    )
开发者ID:SoVictor,项目名称:Lerna,代码行数:14,代码来源:util.py

示例12: __repr__

    def __repr__(self):
        import textwrap

        repr = '{cls}(id={id}, "{text}")'
        args = {
                'cls': self.__class__.__name__,
                'id': hex(id(self))[-4:],
        }
        try:
            args['text'] = textwrap.shorten(self.text, width=10, placeholder='...')
        except:
            repr = '{cls}(id={id})'

        return repr.format(**args)
开发者ID:kxgames,项目名称:glooey,代码行数:14,代码来源:text.py

示例13: truncate

    def truncate(self, length: int = 75, suffix: str = None) -> 'String':
        """
        Returns the string truncated to fit the given length.

        Args:
            length: The position to truncate the string
            suffix: The string to add after the truncated string

        Returns:
            The truncated string
        """
        return String(textwrap.shorten(self,
                                       width=length,
                                       placeholder=suffix or '...'))
开发者ID:paulofreitas,项目名称:dtb-ibge,代码行数:14,代码来源:types.py

示例14: style_tweet

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:erlehmann,项目名称:twtxt2,代码行数:16,代码来源:helper.py

示例15: set_pastes

def set_pastes():
    pastes = list(db.get_pastes())

    for index, element in enumerate(paste_elements):
        # To few pastes available
        if index >= len(pastes):
            element["text"].config(text="")
            element["date"].config(text="")
            element["button"].config(text="")
            element["button"].bind("<Button-1>", lambda x: None)
            element["button"].lower()
            continue

        element["text"].config(text=textwrap.shorten(pastes[index].text, width=50, placeholder="..."))
        element["date"].config(text=pastes[index].date.strftime("%d. %B %Y %H:%M:%S"))
        element["button"].config(text="Copy")
        element["button"].bind("<Button-1>", lambda x: copy_from_history(pastes[index].text))
开发者ID:Arya04,项目名称:hello-world,代码行数:17,代码来源:gui.py


注:本文中的textwrap.shorten函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。