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


Python text.Truncator类代码示例

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


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

示例1: post_loop

def post_loop(max_posts):
    posts = Post.objects.filter(
        status__title="Published").order_by('-post_date')[:max_posts]

    output = ""

    for x in range(0, len(posts)):
        post = posts[x]
        permalink = functions.permalink(post.category.slug, post.slug)
        summary = Truncator(post.content_html)
        properties = {
            'TITLE': post.title,
            'TITLE_LINK': functions.make_link(permalink, post.title),
            'PERMALINK': permalink,
            'BODY': mark_safe(summary.words(100, html=True)),
            'CATEGORY': post.category,
            'POST_DATE': post.post_date,
            'CREATED_DATE': post.created,
            'LAST_EDIT_DATE': post.last_edited,
            'AUTHOR': post.author,
            'LAST_EDITOR': post.last_editor,
        }
        output += render_to_string(
            functions.get_template_file_path("postloop"), properties)

    return output
开发者ID:garetmckinley,项目名称:django-bones,代码行数:26,代码来源:bones_posts.py

示例2: offers

    def offers(doc, categories):
        queryset = Product.objects.filter(is_visible=True, is_retail=True, quantity__gt=0, price__gt=0)
        doc.write('<offers>')
        for product in queryset:
            try:
                category_id = product.categories.filter(parent__isnull=False, id__in=categories).values_list('id', flat=True)[0]
            except IndexError:
                try:
                    category_id = product.categories.filter(parent__isnull=True, id__in=categories).values_list('id', flat=True)[0]
                except IndexError:
                    continue

            text = product.description.strip()
            if text:
                text = strip_tags(strip_spaces_between_tags(product.description)).strip()
                text = typograph(WHITESPACE_RE.sub(' ', text))
                truncator = Truncator(text)
                text = truncator.chars(512)

            doc.write('<offer>')
            doc.write('<url>http://tomat-podarky.ru{}</url>'.format(product.get_absolute_url()))
            doc.write('<price>{}</price>'.format(product.price))
            doc.write('<currencyId>RUR</currencyId>')
            doc.write('<categoryId>{}</categoryId>'.format(category_id))
            doc.write('<delivery>true</delivery>')
            doc.write('<name>')
            doc.write(_(typograph(product.title)))
            doc.write('</name>')
            if text:
                doc.write('<description>')
                doc.write(_(text))
                doc.write('</description>')
            doc.write('</offer>\n')
        doc.write('</offers>')
开发者ID:Lisaveta-K,项目名称:lisaveta-k.github.io,代码行数:34,代码来源:products_yandex_yml.py

示例3: find_post_content

def find_post_content(feed_obj, entry):
    """Find the correct content field for a post."""
    try:
        content = entry["content"][0]["value"]
    except (IndexError, KeyError):
        content = entry.get("description") or entry.get("summary") or ""

    if '<img' not in content:
        # if there's no image and the we add an image to the feed
        def build_img(img_dict):
            try:
                # The tag is url instead of src... pain
                img = "<img src='%s'" % img_dict.get("url")
            except KeyError:
                return ''
            img_dict.pop('url')
            for attr in img_dict.items():
                img += "%s='%s'" % (attr[0], attr[1])
            img += ">"
            return img

        try:
            thumbnail = entry["media_thumbnail"][0]
            img = build_img(thumbnail)
        except (IndexError, KeyError):
            img = ""
        content = img + content
    try:
        truncator = Truncator(text=content)
        content =truncator.words(num=conf.DEFAULT_ENTRY_WORD_LIMIT, html=True)
    except UnicodeDecodeError:
        content = ""

    return feed_content_optimizer.optimize(content)
开发者ID:jo-soft,项目名称:django-feeds,代码行数:34,代码来源:feedutil.py

示例4: save_plugin_data

    def save_plugin_data(self, request=None):
        """Save plugin data.

        We want to save the generated lorem ipsum text for later use.
        Thus, although we don't show it to the user, in case when
        ``generate_lipsum`` field is set to True, we silently generate the
        text and save it into the plugin data.
        """
        if self.cleaned_data.get('generate_lipsum', None):
            lipsum_language = self.cleaned_data.get('lipsum_language', None)
            try:
                if lipsum_language in LANGUAGE_CHOICES_KEYS:
                    if lipsum_language == 'en':
                        gen = Generator()
                    else:
                        gen = TranslipsumGenerator(
                            language_code=lipsum_language
                        )
                    text = gen.generate_paragraph()
                    truncator = Truncator(text)
                    self.cleaned_data['text'] = truncator.chars(
                        self.cleaned_data.get('lipsum_max_chars',
                                              DEFAULT_MAX_CHARS)
                    )
            except Exception as err:
                if DEBUG:
                    logger.debug(err)
开发者ID:barseghyanartur,项目名称:django-dash,代码行数:27,代码来源:forms.py

示例5: tooltip_ellipsis

def tooltip_ellipsis(source, length=0):
    ''' return the plain text representation of markdown encoded text.  That
    is the texted without any html tags.  If ``length`` is 0 then it
    will not be truncated.'''
    try:
        length = int(length)
    except ValueError:  # invalid literal for int()
        return source  # Fail silently.
    ellipsis = '<a href rel="tooltip" title="{0}">...</a>'.format(source)
    truncated = Truncator(source).chars(length + 2, truncate='{...}')
    return mark_safe(truncated.replace('{...}', ellipsis))
开发者ID:etalab,项目名称:youckan,代码行数:11,代码来源:bootstrap.py

示例6: _get_teaser

    def _get_teaser(self):
        """
        Retrieve some part of the article or the article's description.
        """
        if not self._teaser:
            if len(self.description.strip()):
                self._teaser = self.description
            else:
                truncator = Truncator(self.rendered_content)
                self._teaser = truncator.words(WORD_LIMIT, html=True)

        return self._teaser
开发者ID:fatbox,项目名称:django-articles,代码行数:12,代码来源:models.py

示例7: scrape_data

def scrape_data(long_url):
    hdr = {"User-Agent": "Mozilla/5.0"}
    req = urllib2.Request(long_url, headers=hdr)
    response = urllib2.urlopen(req)
    soup = BeautifulSoup(response, "html.parser")

    title = soup.title.string

    meta_tags = soup.findAll("meta", {"property": "og:description"})
    og_desc = meta_tags[0].get("content", "No description")
    description = Truncator(og_desc).chars(200)

    return {"title": title.encode("utf-8"), "description": description.encode("utf-8")}
开发者ID:danielce,项目名称:urlshortener,代码行数:13,代码来源:tasks.py

示例8: avoid_truncated_word

 def avoid_truncated_word(self, text): 
     """Truncate in a way that text will be shorter than max_length and won't be cut in the middle of a word""" 
     words = text.split()
     if not words:
         return text
     truncator = Truncator(text)
     last_word = text.split()[-1]
     text = truncator.chars(self.max_length, '')
     truncated_last_word = text.split()[-1]
     if truncated_last_word !=  last_word: 
         # last word is cut. So, remove it
         num_words = len(text.split())
         text = truncator.words(num_words - 1) 
     return text
开发者ID:clabra,项目名称:awesome-slugify,代码行数:14,代码来源:main.py

示例9: popover_ellipsis

def popover_ellipsis(source, length=0):
    ''' return the plain text representation of markdown encoded text.  That
    is the texted without any html tags.  If ``length`` is 0 then it
    will not be truncated.'''
    try:
        length = int(length)
    except ValueError:  # invalid literal for int()
        return source  # Fail silently.
    ellipsis = ('<a href rel="popover" data-content="{0}" '
        'data-trigger="hover" data-container="body">...</a>').format(escape(source))
    truncated = Truncator(strip_tags(source)).chars(length)
    nb_words = len(truncated.split(' '))
    html_truncated = Truncator(source).words(nb_words, html=True, truncate='{...}')
    return mark_safe(html_truncated.replace('{...}', ellipsis))
开发者ID:etalab,项目名称:youckan,代码行数:14,代码来源:bootstrap.py

示例10: truncate_chars

def truncate_chars(data, maxlen):
    """
    Truncate string to at most ``maxlen``, including elipsis.
    * uses django.utils.text Truncator class.

    :param data: string to truncate
    :param maxlen: length to truncate to
    :returns: string (truncated if necessary)
    """
    from django.utils.text import Truncator

    if isinstance(data, six.text_type) and len(data) > maxlen:
        truncator = Truncator(data)
        data = truncator.chars(maxlen)
    return data
开发者ID:shuiziliu,项目名称:django-garage,代码行数:15,代码来源:text_utils.py

示例11: describe_operation

 def describe_operation(operation, backwards):
     """Return a string that describes a migration operation for --plan."""
     prefix = ''
     if hasattr(operation, 'code'):
         code = operation.reverse_code if backwards else operation.code
         action = code.__doc__ if code else ''
     elif hasattr(operation, 'sql'):
         action = operation.reverse_sql if backwards else operation.sql
     else:
         action = ''
         if backwards:
             prefix = 'Undo '
     if action is None:
         action = 'IRREVERSIBLE'
         is_error = True
     else:
         action = str(action).replace('\n', '')
         is_error = False
     if action:
         action = ' -> ' + action
     truncated = Truncator(action)
     return prefix + operation.describe() + truncated.chars(40), is_error
开发者ID:GravyHands,项目名称:django,代码行数:22,代码来源:migrate.py

示例12: label_for_value

 def label_for_value(self, value):
     key = self.rel.get_related_field().name
     obj = self.rel.to._default_manager.get(**{key: value})
     trunc = Truncator(obj)
     return trunc.words(obj, 14)
开发者ID:annapaula,项目名称:arquea,代码行数:5,代码来源:widgets.py

示例13: ellipse_text

def ellipse_text(text, max_chars):
    truncate = Truncator(text)

    return truncate.chars(max_chars, u"\u2026")
开发者ID:ianmintz,项目名称:pourover,代码行数:4,代码来源:utils.py

示例14: title

 def title(self):
     truncator = Truncator(self.topics)
     return truncator.words(12)
开发者ID:JoeyHa,项目名称:Open-Knesset,代码行数:3,代码来源:models.py

示例15: __unicode__

 def __unicode__(self):
     truncator = Truncator(self.message)
     return u'%s: %s' % (self.id, truncator.chars(20))
开发者ID:Nobody109,项目名称:django-js-error-logging,代码行数:3,代码来源:models.py


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