'Python code saying: "min() arg is an empty sequence"
I am trying to create a function in python to generate and find tweets. But when i call this defined function I get a strange error saying min() arg is an empty sequence. I have attached the definition and the calling functions below.
import re
import json
import xml
import numpy as np
from collections import Counter
!pip install TwitterAPI
from TwitterAPI import TwitterAPI
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression
import requests
# disabling urllib3 warnings
requests.packages.urllib3.disable_warnings()
import matplotlib.pyplot as plt
%matplotlib inline
keywords = ["donkey", "condition", "motion"] # INSERT YOUR CODE
print(keywords)
ONSUMER_KEY = "xL6gbYUG6uNteXxtaVzSopZOe"
CONSUMER_SECRET =
"tvH5dzMtDeZ5u8Tvw2fxq8sCnWU07KenVXcNAEplKBD4uu6AlG"
OAUTH_TOKEN = "1260044898767495170-i60LmXDg7XtEGaiBiTtBXNhSTtRHVk"
OAUTH_TOKEN_SECRET = "L7yCVjWRB9MJhJL0kmnc5DWHlgYfaslrPWLybcXZyswkv"
# Authenticating with your application credentials
api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET, api_version='2')
print(api)
PLACE_LAT = 32.7767 # INSERT YOUR CODE
PLACE_LON = -96.797 # INSERT YOUR CODE
DELTA_LAT = 1.0
DELTA_LON = 1.0
def retrieve_tweets(api, keyword, batch_count, total_count, latitude,
longitude, delta_lat, delta_lon):
"""
collects tweets using the Twitter search API
api: Twitter API instance
keyword: search keyword
batch_count: maximum number of tweets to collect per each request
total_count: maximum number of tweets in total
latitude: latitude of the location centre from where tweets
are retrieved
longitude: longitude of the location centre from where tweets
are retrieved
delta_lat: latitude delta (from the location centre) in degrees
delta_lon: longitude delta (from the location centre) in
degrees
"""
# the collection of tweets to be returned
tweets_unfiltered = []
tweets = []
# the number of tweets within a single query
batch_count = str(batch_count)
'''
You are required to insert your own code where instructed to
perform the first query to Twitter API.
Hint: revise the practical session on Twitter API on how to
perform query to Twitter API.
'''
resp = api.request('tweets/search/recent', {'query': keyword, #
INSERT YOUR CODE
'max_results': total_count, #
INSERT YOUR CODE
'tweet.fields': {'lang':'en'},
'place.fields':{
'geo': {
"type": "Feature",
"bbox": [
longitude - delta_lon,
latitude - delta_lat,
longitude + delta_lon,
latitude + delta_lat
],
"properties": {}
}}})
# check first if there was an error
if ('errors' in resp.json()):
errors = resp.json()['title']
if (errors == 'Invalid Request'):
print('Too many attempts to load tweets or too many
tweets to load.')
print('You need to wait for a few minutes before
accessing Twitter API again or reduce max_results.')
if ('statuses' in resp.json()):
tweets_unfiltered += resp.json()['statuses']
tweets = [tweet for tweet in tweets_unfiltered if
((tweet['retweeted'] != True) and ('RT @' not in
tweet['text']))]
# find the max_id_str for the next batch
ids = [tweet['id'] for tweet in tweets_unfiltered]
max_id_str = str(min(ids))
# loop until as many tweets as total_count is collected
number_of_tweets = len(tweets)
while number_of_tweets < total_count:
resp = api.request('search/tweets', {'q': keyword,
'count': total_count,
'lang':'en',
'result_type': 'recent',
'max_id': max_id_str,
'geocode':'{},{},
{}mi'.format(latitude,
longitude, delta_lat, delta_lon)}) #INSERT YOUR CODE
if ('statuses' in resp.json()):
tweets_unfiltered += resp.json()['statuses']
tweets = [tweet for tweet in tweets_unfiltered if
((tweet['retweeted'] != True) and ('RT @' not in
tweet['text']))]
ids = [tweet['id'] for tweet in tweets_unfiltered]
max_id_str = str(min(ids))
number_of_tweets = len(tweets)
print("{} tweets are collected for keyword {}. Last tweet
created at {}".format(number_of_tweets,
keyword,
tweets[number_of_tweets-1]['created_at']))
ids = [int(tweet['id']) for tweet in tweets_unfiltered]
max_id_str = str(min(ids))
tweets = [tweet for tweet in tweets_unfiltered if (('RT @' not in
tweet['text']) & (tweet['lang'] == 'en'))]
# loop until as many tweets as total_count is collected
number_of_tweets = len(tweets)
while number_of_tweets < total_count:
resp = api.request('tweets/search/recent', {'query': keyword,
# INSERT YOUR CODE
'max_results':total_count,
'until_id': max_id_str,
'tweet.fields':
{'lang':'en'},
'place.fields':{
'geo': {
"type": "Feature",
"bbox": [
longitude - delta_lon,
latitude - delta_lat,
longitude + delta_lon,
latitude + delta_lat
],
"properties": {}
}}})
tweets_unfiltered += resp
tweets = [tweet for tweet in tweets_unfiltered if (('RT @'
not in tweet['text']) & (tweet['lang'] == 'en'))]
ids = [int(tweet['id']) for tweet in tweets_unfiltered]
max_id_str = str(min(ids))
number_of_tweets = len(tweets)
print("{} tweets are collected for keyword {}.
".format(number_of_tweets, keyword))
return tweets
k1_tweets = retrieve_tweets(api,'donkey',50,200,PLACE_LAT,PLACE_LON,
DELTA_LAT, DELTA_LON )
k2_tweets =
retrieve_tweets(api,'condition',50,200,PLACE_LAT,PLACE_LON,
DELTA_LAT, DELTA_LON)
k3_tweets = retrieve_tweets(api,'motion',50,200,PLACE_LAT,PLACE_LON,
DELTA_LAT, DELTA_LON)
I have edited the code to add the rest of it.
If someone knows what is causing tje error it would be great.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|