我(主要是尝试学习python和json,但也)试图定期从twitter中提取和格式化一系列热门话题。我拼凑了很多不同的教程。它符合我的目的 - 打印我需要stdout的HTML,但我想知道我是否可以不同地考虑对象或更好地构造它。协助?
class trend:
#these are the fields that Twitter provides, so they make up one trend.
def __init__(self, query, name, promoted_content, events, url):
self.query = query
self.name = name
self.promoted_content = promoted_content
self.events = events
self.url = url
def listitem(self):
print "\t <li><a href=\"%s\">%s</a></li>\n" %(self.url, self.name)
class trending:
def __init__(self,api_url,title):
self.api_url = api_url
self.title = title
def get_trending(self):
import simplejson as json
import urllib2
trends_all = json.loads(urllib2.urlopen(self.api_url).read())
# test print
# print trends_all[0]['trends']
print "<p>%s</p> \n <ol>" % self.title
#I'm initializing an array, though I don't actually use it. That's next.
trends = []
for x in trends_all[0]['trends']:
thistrend = trend(x['query'], x['name'], x['promoted_content'], x['events'], x['url'])
thistrend.listitem()
trends.append(thistrend)
print "</ol>\n"
return trends
usa = trending("http://api.twitter.com/1/trends/23424977.json","Trending nationally")
usa.get_trending()
反馈
答案 0 :(得分:1)
在你的例子中,我不明白为什么趋势需要成为一个clas,因为它只有一个函数。这可以用get_trending
作为独立函数编写,它将api_url和title作为参数。