File size: 2,303 Bytes
d8ea28c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import streamlit as st
import tweepy as tw
import pandas as pd
from transformers import pipeline
import os

consumer_key = 'OCgWzDW6PaBvBeVimmGBqdAg1'
consumer_secret = 'tBKnmyg5Jfsewkpmw74gxHZbbZkGIH6Ee4rsM0lD1vFL7SrEIM'
access_token = '1449663645412065281-LNjZoEO9lxdtxPcmLtM35BRdIKYHpk'
access_token_secret = 'FL3SGsUWSzPVFnG7bNMnyh4vYK8W1SlABBNtdF7Xcbh7a'

auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)
classifier = pipeline('sentiment-analysis')

# Define file name and headers
FILE_NAME = 'query_history.csv'
HEADERS = ['Search Query', 'Number of Tweets', 'Results', 'Date']

# Create file if it does not exist
if not os.path.isfile(FILE_NAME):
    df = pd.DataFrame(columns=HEADERS)
    df.to_csv(FILE_NAME, index=False)

# Make program take up full width of screen
st.set_page_config(page_title='πŸ˜ƒ Twitter Sentiment Analysis', layout='wide')

# Define function to display history
def display_history():
    df = pd.read_csv(FILE_NAME)
    st.dataframe(df.style.highlight_max(axis=0))

# Define main function
def run():
    with st.form(key='Enter name'):
        search_words = st.text_input('Enter a word or phrase you want to know about')
        number_of_tweets = st.number_input('How many tweets do you want to see? (maximum 50)', 0,50,10)
        submit_button = st.form_submit_button(label='Submit')

    if submit_button:
        tweets =tw.Cursor(api.search_tweets,q=search_words,lang="en").items(number_of_tweets)
        tweet_list = [i.text for i in tweets]
        p = [i for i in classifier(tweet_list)]
        q=[p[i]['label'] for i in range(len(p))]
        df = pd.DataFrame(list(zip([search_words], [number_of_tweets], [tweet_list], [pd.Timestamp.now()])),columns = HEADERS)
        st.write(pd.DataFrame(list(zip(tweet_list, q)),columns =['Latest '+str(number_of_tweets)+' Tweets'+' on '+search_words, 'sentiment']))
        with open(FILE_NAME, mode='a', newline='') as file:
            df.to_csv(file, header=False, index=False)
            
    if st.button('Clear History'):
        os.remove(FILE_NAME)
        st.write('History has been cleared.')
        
    if st.button('Display History'):
        display_history()

if __name__=='__main__':
    run()