我正在实施将{Tweet}写入CSV的Tweepy Twitter Streamer。
这很好用。
如果我正在处理简单的功能,我可以很容易地解决这个问题。对于Python类来说有些新手,我很挣扎。
我尝试在类中使用def __init__(self, keyword):
语法。如果我将类视为标准对象,这似乎有效。如果我尝试实现Tweepy,它会破坏代码。我的猜测是我没有正确地尝试这个和/或Tweepy StreamListener类不是为了接受关键字参数而设计的。
我已经注释了我尝试传递关键字的细节
import csv
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
#Insert Your Twitter Credentials Here
from mycredentials import *
#Set Authorization
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)
class TwitterListener(StreamListener):
#Broken Attempt
#def __init__(self, keyword):
# self.keyword = keyword
def start_csv():
#Broken Attempt
#filename = str(self.keyword)+".csv"
#with open(filename, 'a') as f:
with open('Clinton.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(["DATE", "AUTHOR", "TWEET"])
def on_status(self, status):
try:
#Broken Attempt
#filename = str(self.keyword)+".csv"
#with open(filename, 'a') as f:
with open('Clinton.csv', 'a') as f:
writer = csv.writer(f)
#Tweet Content
author = str(status.author.screen_name.encode('utf-8'))
date = str(status.created_at)
tweet = str(status.text.encode('utf-8'))
print(date, tweet)
writer.writerow([date, author, tweet])
except Exception as error:
print(error)
def on_error(self, status_code):
print(status_code)
#Broken Attempt
#twitterStream = Stream(auth, TwitterListener("test"))
#Works
twitterStream = Stream(auth, TwitterListener())
twitterStream.filter(track=['#Clinton'])
答案 0 :(得分:0)
当您覆盖类的__init__
方法时,需要调用超类的__init__
方法。
您的__init__
方法应如下所示:
def __init__(self, keyword):
super(TwitterListener, self).__init__()
# Your code here
self.keyword = keyword