1
\$\begingroup\$

My concern with this code is the excessive use of .encode('utf-8'). Any advice on refining these functions would be very helpful.

rss2html GitHub repo

#!/usr/bin/env python

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

from feedparser import parse as parsefeed
import StringIO


def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)


def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >>out, entry2html(title=title, link=link,
                                description=description)
    return out.getvalue()

print convert_feed(url='http://stackoverflow.com/feeds')
\$\endgroup\$
  • 1
    \$\begingroup\$ I've removed your new version of the code, since it adds confusion to the question. If you would like further advice, feel free to ask another question. \$\endgroup\$ – 200_success May 4 '14 at 7:04
3
\$\begingroup\$

Work in Unicode and encode at the last moment:

def entry2html(**kwargs):
    """ Format feedparser entry """
    template = u"""
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(**kwargs)

def convert_feed(**kwargs):
    """ Main loop """
    out = u'\n'.join(entry2html(**entry) 
                    for entry in parsefeed(kwargs['url']).entries)
    return out.encode('utf-8')

You can pass entry directly as format does not mind extra keyword arguments. StringIO is not necessary for simple concatenation of strings.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.