2014-02-24 39 views
0

菜鳥用戶蟒:Tweepy搜索的API寫入文件錯誤

我創建的文件提取基礎上,api.search(不流API)10個鳴叫。我得到一個屏幕結果,但無法計算如何解析輸出以保存到csv。我的錯誤是TypeError:期望一個字符緩衝區對象。

我一直在使用。加入(STR(x)和獲得其他錯誤嘗試。

我的代碼是

import tweepy 
import time 
from tweepy import OAuthHandler 
from tweepy import Cursor 

#Consumer keys and access tokens, used for Twitter OAuth 
consumer_key = '' 
consumer_secret = '' 
atoken = '' 
asecret = '' 

# The OAuth process that uses keys and tokens 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(atoken, asecret) 

# Creates instance to execute requests to Twitter API 
api = tweepy.API(auth) 

MarSec = tweepy.Cursor(api.search, q='maritime security').items(10) 

for tweet in MarSec: 
    print " " 
    print tweet.created_at, tweet.text, tweet.lang 

saveFile = open('MarSec.csv', 'a') 
saveFile.write(tweet) 
saveFile.write('\n') 
saveFile.close() 

任何幫助,將不勝感激。我已經得到了我的流API的工作,但我有這一個難題。

感謝。

回答

1

tweet不是一個字符串或字符緩衝區。這是一個對象。與更換你行,你會很開心。

saveFile = open('MarSec.csv', 'a') 
for tweet in MarSec: 
    print " " 
    print tweet.created_at, tweet.text, tweet.lang 
    saveFile.write("%s %s %s\n"%(tweet.created_at, tweet.lang, tweet.text)) 

saveFile.close() 
+0

嗨,我已經試過了,它只成功了一個推文(最後一個),但我想返回3個項目的全部數據集:文本,created_at和我的輸出文件中的語言。感謝並仍然難倒。 – Codesurfer

+0

'tweet'只存在於循環內,將文字移動到那裏,並且應該完成。 – aIKid

+0

非常感謝。進入循環並且現在起作用。我遇到了一個新的錯誤UnicodeEncodeError:'ascii'編解碼器無法在位置159編碼字符u'\ u2026':序號不在範圍內(128),我將在明天進行研究。 – Codesurfer

1

我只是想我會忍受另一個版本對於那些誰可能要保存一個tweepy.models.Status對象的所有 的屬性,如果你還沒有確保每個鳴叫的哪些屬性要保存到文件。

import json 

search_results = [] 
for status in tweepy.Cursor(api.search, q=search_text).items(5000): 
    search_results.append(status._json) 

with open('search_results.json', 'w') as f: 
    json.dump(search_results, f) 

第一座將搜索結果存儲到字典的列表,和第二塊將輸出所有的鳴叫成JSON文件。 請注意,如果搜索結果的大小很大,這可能會佔用大量內存。

+0

status._json對象的近似大小是多少? –