I have a function which uses matplotlib and pandas to crunch tweets from txt file and plot a graph.
I'm using that script in views.py
in django.
It shows the output correctly the first time, however on executing the webpage second time leads to an infinite loop.
I am trying to figure out the reason but can't solve it.
Here is the views.py
function:
def main():
print 'Reading Tweets\n'
tweets_data_path = 'twitter_data.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
print 'Structuring Tweets\n'
tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
print 'Adding programming languages tags to the data\n'
tweets['python'] = tweets['text'].apply(
lambda tweet: word_in_text('python', tweet)
)
tweets['javascript'] = tweets['text'].apply(
lambda tweet: word_in_text('javascript', tweet)
)
tweets['ruby'] = tweets['text'].apply(
lambda tweet: word_in_text('ruby', tweet)
)
print 'Analyzing tweets by programming language\n'
prg_langs = ['python', 'javascript', 'ruby']
tweets_by_prg_lang = [
tweets['python'].value_counts()[True],
tweets['javascript'].value_counts()[True],
tweets['ruby'].value_counts()[True]
]
x_pos = list(range(len(prg_langs)))
width = 0.8
fig, ax = plt.subplots()
plt.bar(x_pos, tweets_by_prg_lang, width, alpha=1, color='g')
ax.set_ylabel('Number of tweets', fontsize=15)
ax.set_title('Ranking:', fontsize=10, fontweight='bold')
ax.set_xticks([p + 0.4 * width for p in x_pos])
ax.set_xticklabels(prg_langs)
plt.grid()
plt.show()
return render('analytics.html')
This is the url which calls the main function:
url(r'^analytics/$', 'newsletter.analytics.main', name='analytics'),
It executes in terminal as many times as i want. But stuck in webpages. Please shed some light on me !! P.S i am new to Django