[Tutor] help writing functions

Saad Javed sbjaved at gmail.com
Thu Feb 23 01:59:01 CET 2012


I am learning python and need guidance for writing some code. I've written
a simple program (with pointers from people) that parses an tv show xml
feed and prints their values in plain text after performing some string
operations.

[CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed
tree = etree.parse(feed)
x = tree.xpath("/rss/channel/item/title/text()")
x = str(x[0])
for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc
x = re.sub(r'\b' + tag + r'\b', '', x)
z = re.sub(r'[^\w\s]', '', x)
y = tree1.xpath("/rss/channel/item/pubDate/text()")
print "%s - %s" %(z.rstrip(), y[0][:16])[/CODE]

The code works fine (prints the name of the show and date). Now since I am
parsing more than one feed, I thought the better way was to split the
functionality into diff functions: one to get the values and the other to
remove the tags. I'm still *very* new to python and came up with the
following code.

[CODE]def get_value(feed):
try:
url = urllib2.urlopen(feed)
 tree = etree.parse(url)
x = tree.xpath("/rss/channel/item/title/text()")
 y = tree.xpath("/rss/channel/item/pubDate/text()")
x = str(x[0])
 y = str(y[0][:16])
return x
return y
 except SyntaxError:
print 'Service Unavailable'
pass

def del_tag(x):
tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P',
'IMMERSE', '720p', 'X264']
 for tag in tags:
x = re.sub(r'\b' + tag + r'\b', '', x)
 y = re.sub(r'[^\w\s]', '', x)
def main():
a = get_value(rssPage)
 b = del_tag(a)
print b
 if __name__ == '__main__':
main()[/CODE]

My desired working is to supply the xml feed address to the
[B]get_value[/B] function which returns the title and date as strings
assigned to [B]x[/B] and [B]y[/B]. Then I run the [B]del_tag[/B] function
on the title string ([B]x[/B]) and remove tags and the [B]main()[/B]
function prints both [B]x[/B] and [B]y[/B] (Title, Date).

Running this code returns [B]None[/B].

Let the teaching begin :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120223/149e067d/attachment-0001.html>


More information about the Tutor mailing list