2013-12-07 31 views
0

下面是我一直在努力的代碼。我是新來的Python和編程,並一直試圖教我自己。Python「變量未定義」錯誤當它是

我收到以下錯誤消息。但messages被定義,所以我不明白。

[[email protected] ~]$ ./twitter_test16.sh 
Traceback (most recent call last): 
    File "./twitter_test16.sh", line 53, in <module> 
    write_csv('twitter_gmail.csv', messages, append=True) 
NameError: name 'messages' is not defined 

代碼:

import csv 
import json 
import oauth2 as oauth 
import urllib 
import sys 
import requests 
import time 

CONSUMER_KEY = "" 
CONSUMER_SECRET = "" 
ACCESS_KEY = "" 
ACCESS_SECRET = "" 

class TwitterSearch: 
    def __init__(self, 
     ckey = CONSUMER_KEY, 
     csecret = CONSUMER_SECRET, 
     akey = ACCESS_KEY, 
     asecret = ACCESS_SECRET, 
     query = 'https://api.twitter.com/1.1/search/tweets.{mode}?{query}' 
    ): 
     consumer  = oauth.Consumer(key=ckey, secret=csecret) 
     access_token = oauth.Token(key=akey, secret=asecret) 
     self.client = oauth.Client(consumer, access_token) 
     self.query = query 

    def search(self, q, mode='json', **queryargs): 
     queryargs['q'] = q 
     query = urllib.urlencode(queryargs) 
     return self.client.request(self.query.format(query=query, mode=mode)) 

def write_csv(fname, rows, header=None, append=False, **kwargs): 
    filemode = 'ab' if append else 'wb' 
    with open(fname, filemode) as outf: 
     out_csv = csv.writer(outf, **kwargs) 
     if header: 
      out_csv.writerow(header) 
     out_csv.writerows(rows) 

def main(): 
    ts = TwitterSearch() 
    response, data = ts.search('@gmail.com', result_type='recent') 
    js = json.loads(data) 


    # I need to parse the content in js and turn it into a generator expression 
    messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', [])) 
    # 

write_csv('twitter_gmail.csv', messages, append=True) 

我有「定義的消息」,所以我不知道爲什麼我收到一個錯誤,告訴我「的消息」沒有定義。

回答

8

因爲線write_csv('twitter_gmail.csv', messages, append=True)不是部分main()函數。該行根本沒有縮進,因此Python將其視爲main()函數後面的單獨代碼行,並在運行此腳本時立即執行。

縮進該行以匹配messages線,並且不要忘記呼叫main()

def main(): 
    ts = TwitterSearch() 
    response, data = ts.search('@gmail.com', result_type='recent') 
    js = json.loads(data) 

    messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', [])) 
    write_csv('twitter_gmail.csv', messages, append=True) 

if __name__ == '__main__': 
    main() 
+0

太謝謝你了。這使得總的感覺調用main()。正如我一直在教自己編碼,這個網站已經幫了我很多。真的很感激它! – user2748540