2014-10-28 52 views
1

我試圖篩選與白銀情感分析鳴叫Twitter的流...Python-twitterstream。過濾元組錯誤

class listener(StreamListener): 
    def on_data(self, data): 
     try: 
      tweet = json.loads(data) 
      print (tweet['created_at'], tweet['text']) 

      alchemyapi = AlchemyAPI() 
      response = alchemyapi.sentiment('text', tweet['text']) 
      print "Sentiment: ", response["docSentiment"]["type"] 

      dictionary={} 
      dictionary['tweet'] = tweet['text'] 
      dictionary['id'] = tweet['id'] 
      dictionary['created_at'] = tweet['created_at'] 
      dictionary['sentiment'] = response["docSentiment"]["type"] 
      json_data = json.dumps(dictionary) 

      saveFile = open('silverTweetFeed.json','a') #a=append 
      saveFile.write(json_data) 
      saveFile.write('\n') 
      saveFile.close() 
      return True 

     except BaseException, e: #baseException because there may be a rate limit or internet drop 
      print 'failed ondata,',str(e) 
      time.sleep(5) 

    def on_error(self, status): 
     print status 

auth = OAuthHandler(ckey, csecret) 
auth.set_access_token(atoken,asecret) 
twitterStream = Stream(auth, listener()) 
twitterStream.filter(track=["silver" and "CFD" or "invest" or "bloomberg" or "DFT" or "rally"or 
     "hike" or "investors" or "demand" or "interest rate" or "inflation" or 
     "bullion" or "trading" or "investment" or "market"]) 
twitterStream.filter(languages=["en"]) 

但是當我運行這個它拋出一個錯誤...

/PythonFiles/silverScript.py", line 49, in <module> 
"investors", "demand", "interest rate", "inflation", "bullion", "trading", "investment", "market")]) 
    File "build/bdist.macosx-10.9-intel/egg/tweepy/streaming.py", line 330, in filter 
AttributeError: 'tuple' object has no attribute 'encode' 
logout 

任何人都可以提出更有效的過濾技術或幫助解決這個錯誤?

+0

不完全確定這是否可以完成。我曾嘗試使用邏輯運算符'或',但它會拋出相同的錯誤 – Adam 2014-10-28 11:25:32

回答

0

這可以完成。 Twitter stream logic與過濾器邏輯不同。 ’silver bullion’被解釋爲’silver’ AND ‘bullion’,而[‘silver’, ‘bullion’]被解釋爲’silver’ OR ‘bullion’。因此,要篩選所有組合:

twitterStream.filter(track=[‘silver CFD’, ‘silver invest’, ‘silver bloomberg’, ‘silver DFT’, 
          ‘silver rally’, ‘silver hike’, ‘silver investors’, ‘silver demand’, 
          ‘silver interest rate’, ‘silver inflation’, ‘silver bullion’, 
          ‘silver trading’, ‘silver investment’, ‘silver market’]) 

請記住,搜索術語解析爲小寫所以你的大寫字母縮寫將匹配不僅僅是大寫字母縮寫的更多。

+0

謝謝你,這是非常有用的 – Adam 2014-11-10 13:00:53