本文整理汇总了Python中textwrap.shorten函数的典型用法代码示例。如果您正苦于以下问题:Python shorten函数的具体用法?Python shorten怎么用?Python shorten使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了shorten函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: do_tweet
def do_tweet(text, weather_location, tweet_location, variable_location, hashtag=None):
"""
Post a tweet.
If set in the config, a hashtag will be applied to the end of the tweet.
If variable_location is True, prepend the tweet with the location name.
If tweet_location is True, the coordinates of the the location will be embedded in the tweet.
If successful, the status id is returned, otherwise None.
:type text: str
:param text: text for the tweet
:type weather_location: models.WeatherLocation
:param weather_location: location information used for the tweet location and inline location name
:type tweet_location: bool
:param tweet_location: determines whether or not to include Twitter location
:type variable_location: bool
:param variable_location: determines whether or not to prefix the tweet with the location
:type hashtag: str
:param hashtag:
:return: a tweepy status object
"""
api = get_tweepy_api()
body = text
# account for space before hashtag
max_length = 279 - len(hashtag) if hashtag else 280
if variable_location:
body = weather_location.name + ': ' + body
logging.debug('Trying to tweet: %s', body)
if len(body) > max_length:
# horizontal ellipsis
body = textwrap.shorten(body, width=max_length, placeholder='\u2026')
logging.warning('Status text is too long, tweeting the following instead: %s', body)
if hashtag:
body += ' ' + hashtag
try:
if tweet_location:
status = api.update_status(status=body, lat=weather_location.lat, long=weather_location.lng)
else:
status = api.update_status(status=body)
logging.info('Tweet success: %s', body)
return status
except tweepy.TweepError as err:
logging.error('Tweet failed: %s', err.reason)
logging.warning('Tweet skipped due to error: %s', body)
return None
开发者ID:BurgasLAN,项目名称:weatherBot,代码行数:46,代码来源:weatherBot.py
示例17: 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:
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
return "➤ {nick} ({time}):\n{tweet}".format(
nick=click.style(tweet.source.nick, bold=True),
tweet=final_text,
time=click.style(tweet.relative_datetime, dim=True))
开发者ID:s5mccarthy,项目名称:twtxt,代码行数:17,代码来源:helper.py
示例18: handle
def handle(self, sender, target, tokens, bot):
if len(tokens) < 2:
for line in self.help_text:
bot.send_privmsg(sender, line)
return
search_title = ' '.join(tokens[1:])
try:
page = wikipedia.page(search_title)
except wikipedia.exceptions.DisambiguationError as err:
m = 'Your query returned a disambiguation page.'
bot.send_privmsg(sender, m)
if len(err.options) < 6:
m = 'Options: {}'.format(u'; '.join(err.options))
bot.send_privmsg(sender, m)
else:
opts_list = u'; '.join(err.options[:6])
m = 'Some options: {} ...'.format(opts_list)
bot.send_privmsg(sender, m)
return
except wikipedia.exceptions.PageError as err:
bot.send_privmsg(sender, str(err))
return
summ = textwrap.shorten(page.summary, width=300, placeholder=' ...')
m = '{} // {} [ {} ]'.format(page.title, summ, page.url)
if not bot.is_irc_channel(target):
bot.send_privmsg(sender, m)
return
now = int(time.time())
last = int(bot.c.get('wiki:last', 0))
wait = int(bot.c.get('wiki:wait', 0))
if last < now - wait:
bot.send_privmsg(target, m)
bot.c.set('wiki:last', now)
else:
bot.send_privmsg(sender, m)
remaining = last + wait - now
m = 'I am cooling down. You cannot use {}'.format(tokens[0])
m = '{} in {} for another'.format(m, target)
m = '{} {} seconds.'.format(m, remaining)
bot.send_privmsg(sender, m)
开发者ID:khakionion,项目名称:wormgas,代码行数:44,代码来源:wiki.py
示例19: form_valid
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image",'')
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.questionary.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
开发者ID:amadeusproject,项目名称:amadeuslms,代码行数:43,代码来源:views.py
示例20: format_quote
def format_quote(quote, short=False):
"""Returns a human-readable string representation of a Quote object.
:param quote: helga.plugins.quotes.Quote
:param short: bool
:return: str
"""
if short:
return "#{quote_id}: „<{author}> {text}“".format(
quote_id=quote.quote_id,
author=quote.author.first_name,
text=textwrap.shorten(quote.text, 50))
else:
return "Quote #{quote_id}: „<{author}> {text}“ (added by {added_by} at {date})".format(
quote_id=quote.quote_id,
author=quote.author.first_name,
text=quote.text.replace('\n', ' '),
added_by=quote.added_by.first_name,
date=format_timestamp(quote.date))
开发者ID:buckket,项目名称:thelga,代码行数:19,代码来源:helper.py
注:本文中的textwrap.shorten函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论