目标是使用python搜索包含指定单词的推文,获取经纬度坐标并写入.csv。
更新:此刻无论我使用什么关键字,它都将返回“无坐标”。
#All of the consumer keys, tokens, and imports are left out of this sample code.
file = open("C:\Scripts\Output.csv", "w")
file.write("X,Y\n")
data_list = []
count = 0
class listener(StreamListener):
def on_data(self, data):
global count
#How many tweets you want to find, could change to time based
if count <= 2000:
json_data = json.loads(data)
coords = json_data["coordinates"]
if coords is None:
print("no coordinates")
else:
print(coords["coordinates"])
lon = coords["coordinates"][0]
lat = coords["coordinates"][1]
data_list.append(json_data)
file.write(str(lon) + ",")
file.write(str(lat) + "\n")
count += 1
return True
else:
file.close()
return False
def on_error(self, status):
print(status)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream = Stream(auth, listener())
#What you want to search for here
twitterStream.filter(track=["horse"])
预期结果将是一个CSV文件,其中包含带有指定单词“马”的推文的纬度和经度坐标。更新:我尝试输入的任何关键字都返回“无坐标”。
答案 0 :(得分:2)
您有以下条件声明:
if coords is not None:
但是,如果“ coords”为“ None”,则程序不会被捕获。我猜这就是错误所在。
让我知道这是否有帮助!干杯!