我有一个练习Python技能的项目:
我已经能够独立完成所有这些事情。现在,挑战是让一切都协同工作! :)
要更新我的Google电子表格,我使用的是gspread。
但是,要更新单元格,我需要指示单元格的行和列:
worksheet.update_acell('B1', 'Bingo!')
我正在尝试在我的脚本中提取一个计数器来提取推文。目标是在每次发现推文时将B1更改为B2,然后更改为B3,然后更改为B4。
但它不能正常工作......坐标会打印在我的终端上,但就是这样。
我想我没有像我应该的那样使用这个课程。但我不明白我的错误在哪里!
帮助?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy
import gspread
import time
CONSUMER_KEY, CONSUMER_SECRET = 'SECRET', 'SECRET'
USER_KEY, USER_SECRET = 'SECRET', 'SECRET'
class MyStream(tweepy.StreamListener):
def __init__(self):
tweepy.StreamListener.__init__(self)
# I added this to have a counter.
self.n = 2
def on_status(self, tweet):
try:
longitude = str(tweet.coordinates['coordinates'][0])
latitude = str(tweet.coordinates['coordinates'][1])
print longitude
print latitude
# I added this to update my google spreadsheet with the coordinates
self.wks.update_acell(('A' + str(n)), longitude)
self.wks.update_acell(('B' + str(n)), latitude)
print "Spreadsheet updated!"
# This is for my counter
self.n += 1
except:
pass
def main():
#I added these two lines to connect to my google spreadsheet
gc = gspread.login('EMAIL', 'PASSWORD')
wks = gc.open('SPREADSHEET_NAME').sheet1
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(USER_KEY, USER_SECRET)
stream = tweepy.Stream(auth, MyStream(), timeout=50)
stream.filter(locations=[-74.00,45.40,-73.41,45.72])
if __name__ == "__main__":
main()
答案 0 :(得分:2)
我自己在测试时遇到了麻烦(主要是因为我不熟悉tweepy.Stream
如何工作,我认为),但看起来你的MyStream
实例从未得到它首先设置wks
属性。
这意味着当您引用self.wks
时,它可能会引发AttributeError
,但由于您的try
/ except
阻止,您再也看不到它了。 (顺便说一句,这就是为什么except: pass
难以排除故障的原因。)
您可能希望MyStream
采取额外的wks
参数,如下所示:
def __init__(self, wks):
tweepy.StreamListener.__init__(self)
# Store the worksheet on this instance.
self.wks = wks
# I added this to have a counter.
self.n = 2
然后更改实例化MyStream
的行,以便您现在将该工作表作为参数传递:
stream = tweepy.Stream(auth, MyStream(wks), timeout=50)
答案 1 :(得分:2)
我找到了答案!
实际上,@ jonrsharpe和@myersjustinc,你们都是对的!
"周"没有正确设置,我没有使用" self"正确。
谢谢!你的提示帮助我找到答案!
编辑:所以这是工作代码。
class MyStream(tweepy.StreamListener):
def __init__(self):
tweepy.StreamListener.__init__(self)
# I added self wks but also the login step on the same line
self.wks = gspread.login('EMAIL', 'PASSWORD').open('SPREADSHEET').sheet1
# I added this to have a counter.
self.n = 2
def on_status(self, tweet):
try:
longitude = str(tweet.coordinates['coordinates'][0])
latitude = str(tweet.coordinates['coordinates'][1])
print longitude
print latitude
# I added this to update my google spreadsheet with the coordinates
self.wks.update_acell(('A' + str(self.n)), longitude)
self.wks.update_acell(('B' + str(self.n)), latitude)
print "Spreadsheet updated!"
# This is for my counter
self.n += 1