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')
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 3, 2014 at 6:48
\$\endgroup\$
1
  • 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\$ Commented May 4, 2014 at 7:04

1 Answer 1

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.

answered May 3, 2014 at 7:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.