0

我(主要是尝试学习 python 和 json,但也)尝试定期从 twitter 中提取和格式化趋势主题列表。我把这个拼凑起来浏览了很多不同的教程。它符合我的目的——将我需要的 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()

反馈?

4

1 回答 1

1

在您的示例中,我不明白为什么趋势需要成为一个类,因为它只有一个功能。这可以写成get_trending一个独立的函数,它以 api_url 和 title 作为参数。

于 2011-08-31T20:56:28.477 回答