I want to make a piece of code which pulls the title and link off an RSS feed and compiles it into a variable which can be then used in the message body. My problem is Body gets redefined every time i pull the info off the RSS. I am very new to programming and python, and I am under the impression that using a list would be the best thing to do.
for i in range(3):
MessageTitle = feed['items'][i].title
MessageLink = " - ",feed['items'][i]['link']
Body = "%s%s%s%s" % (Messag开发者_运维技巧eTitle,"\n","\n", MessageLink) #in unicode
gmail_user = "user@gmail.com"
gmail_pwd = "pw"
mail("user@gmail.com",
"Reddit Update",
Body)
I was going to insert the list below body, and use body to define it.. something like:
list[i] = [Body]
Am i on the right track?
There are a variety of design patterns you can consider using. I will demonstrate a few where you don't need to use [i]
even:
Accumulator:
messages = []
for feedItem in feed['items']:
message = {'title':..., ...}
message['link'] = ... # alternative
messages += [message] # or messages.append(data)
print(messages)
Mapping (often the most elegant solution in simple cases like this):
def makeMessage(feedItem):
message = {'title':..., ...}
return message
messages = [makeMessage(fi) for fi in feed['items']]
print(messages)
Generators:
def makeMessages(feedItems):
for item in feedItems:
message = {'title':..., ...}
yield message
messages = list( makeMessages(feed['items']) )
unrelated addendum: You might even consider making a class for your messages:
class Message(object):
def __init__(self, title, link, body):
self.title = title
self.link = link
self.body = body
def __str__(self):
return ...
def __repr__(self):
return self.__str__()
精彩评论