\$\begingroup\$
\$\endgroup\$
1
My concern with this code is the excessive use of .encode('utf-8')
. Any advice on refining these functions would be very helpful.
#!/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
-
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– 200_success2014年05月04日 07:04:23 +00:00Commented May 4, 2014 at 7:04
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
lang-py