The progressbar does not show the percentage

hai i have a problem with my progress bar I want to how my bar like this
Capture

However I already got to make the progress bar the issues here when I run test not in the app the it has percentage like this
1

When I implemented in the streamlit code it does not show the percentage

and here my coding:


import pandas as pd
import streamlit as st
import cleantext
import numpy as np
import re
import nltk
import gensim.utils
import time
nltk.download('wordnet')
nltk.download('stopwords')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
from nltk.corpus import stopwords
from gensim.utils import simple_preprocess
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from textblob import TextBlob
from PIL import Image
from streamlit_option_menu import option_menu

im = Image.open(r"C:\Users\Administrator\Documents\UiTM\D3\S6\CSP\image\carat.ico")
st.set_page_config(page_title="FeelTech",page_icon=im,layout="wide")
st.header('Twitter Sentiment Analysis')
st.markdown("##")

df = None
#side bar
st.sidebar.image(r"C:\Users\Administrator\Documents\UiTM\D3\S6\CSP\image\1.jpg",caption="Developed and Maintaned by: Hidayah Athira")
         
#switcher
st.sidebar.header("Twitter Analysis")
def Home():
    with st.expander('Analyze tweets'):
            tweets = st.text_input('tweets here: ')
            if tweets:
                blob = TextBlob(tweets)
                st.write('Polarity: ', round(blob.sentiment.polarity,2))
                st.write('Subjectivity: ', round(blob.sentiment.subjectivity,2))


            pre = st.text_input('Clean tweets: ')
            if pre:
                st.write(cleantext.clean(pre, clean_all= False, extra_spaces=True ,
                                        stopwords=True ,lowercase=True ,numbers=True , punct=True))
    with st.expander('Analyze CSV'):
        upl = st.file_uploader('Upload file')
        if upl:
                df = pd.read_csv(upl)
                st.dataframe(df, use_container_width=True)
                positive_percentage = 0  # Initialize the variables before the if block
                negative_percentage = 0
                neutral_percentage = 0
                if st.button('Clean Data'):
                    
                    #convert all tweet into lowercase
                    df['tweets'] = df['tweets'].str.lower()


                    #Removing Twitter Handles(@User)
                    def remove_users(tweets):
                        remove_user = re.compile(r"@[A-Za-z0-9]+")
                        return remove_user.sub(r"", tweets)


                    df['tweets'] = df['tweets'].apply(remove_users)


                    #Remove links
                    def remove_links(tweets):
                        remove_no_link = re.sub(r"http\S+","",tweets)
                        return remove_no_link


                    df['tweets'] = df['tweets'].apply(remove_links)


                    #Remove Punctuations, Numbers, and Special Characters
                    df['tweets'] = df['tweets'].str.replace("[^a-zA-Z#]", " ")


                    #Remove short words
                    df['tweets'] = df['tweets'].apply(lambda x: ' '.join([w for w in x.split() if len(w)>3]))


                    #Remove hashtag
                    def remove_hashtags(tweets, pattern):
                        r = re.findall(pattern, tweets)
                        for i in r:
                            tweets = re.sub(i, '', tweets)
                        return tweets

                    df['tweets'] = np.vectorize(remove_hashtags)(df['tweets'],"#[\W]*")

                    #Emoji removal
                    def remove_emojis(string):
                        remove_emoji = re.compile("["u"\U0001F600-\U0001F64F"  # emoticons
                                                u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                                                u"\U0001F680-\U0001F6FF"  # transport & map symbols
                                                u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                                                "]+", flags=re.UNICODE)
                        return remove_emoji.sub(r'', string)

                    df['tweets'] = df['tweets'].apply(remove_emojis)


                    #Lemmatization
                    lemmatizer = WordNetLemmatizer()
                    wordnet_map = {"N":wordnet.NOUN, "V":wordnet.VERB, "R":wordnet.ADV}

                    def lemmatize_words(tweets):
                        pos_tagged_tweets = nltk.pos_tag(tweets.split())
                        return " ".join([lemmatizer.lemmatize(word, wordnet_map.get(pos[0], wordnet.NOUN)) for word, pos in pos_tagged_tweets])


                    #Prepare Stop words
                    stop_words = stopwords.words('english')
                    stop_words.extend(['from', 'https', 'twitter', 'still'])

                    def remove_stopwords(tweets):
                        return [[word for word in simple_preprocess(str(tweets)) if word not in stop_words]for tweetss in tweets]

                    df['stop_word'] = remove_stopwords(df['tweets'])


                    #Tokenize Word
                    def tokenize(tweets):
                        for word in tweets:
                            yield(gensim.utils.simple_preprocess(str(word), deacc=True))
                            
                    df['token'] = list(tokenize(df['tweets']))
                    # Function to get sentiment label using TextBlob
                    def label_sentiment(tweets):
                        analysis = TextBlob(tweets)
                        sentiment_score = analysis.sentiment.polarity

                        if sentiment_score > 0:
                            return "positive"
                        elif sentiment_score < 0:
                            return "negative"
                        else:
                            return "neutral"
                    # Apply the labeling function to your DataFrame
                    df['sentiment'] = df['tweets'].apply(label_sentiment)
                     # Calculate percentages
                    total_samples = len(df)
                    positive_percentage = (df['sentiment'] == 'positive').sum() / total_samples *100
                    negative_percentage = (df['sentiment'] == 'negative').sum() / total_samples *100
                    neutral_percentage = (df['sentiment'] == 'neutral').sum() / total_samples *100
                    st.dataframe(df, use_container_width=True)
                
                if st.button('Visualize'):
                    st.markdown("""<style>.stProgress > div > div > div > div { background-image: linear-gradient(to right, #99ff99 , #FFFF00)}</style>""",unsafe_allow_html=True,)
                    # Create progress bars for each sentiment category
                    
                    # Display progress bars
                    st.write("Positive Sentiment:")
                    bar = st.progress(100)
                    time.sleep(0.1)
                    bar.progress(positive_percentage) 
                    st.write(f"{positive_percentage:.2f}%")

                    st.write("Negative Sentiment:")
                    bar = st.progress(100)
                    time.sleep(0.1)
                    bar.progress(negative_percentage) 
                    st.write(f"{negative_percentage:.2f}%")

                    st.write("Neutral Sentiment:")
                    bar = st.progress(100)
                    time.sleep(0.1)
                    bar.progress(neutral_percentage) 
                    st.write(f"{neutral_percentage:.2f}%")
        
def sideBar():

 with st.sidebar:
    selected=option_menu(
        menu_title="Main Menu",
        options=["Home","Dashboard"],
        icons=["house","eye"],
        menu_icon="cast",
        default_index=0
    )
 if selected=="Home":
    #st.subheader(f"Page: {selected}")
    Home()
    
sideBar()

can you help me find where is the error with my coding that does not show the progress?

Hello @hyunshi,

I’ve moved your issue to the ‘Using Streamlit’ section. This is the section where you can raise any issues regarding Streamlit. The “Show the Community” section is here for showcasing projects! :slight_smile:

Thanks,
Charly

ouwhh okay
 Thanks


I’m not able to try the code at the moment, but from a quick glance, I would suggest creating the progress bars outside the if block and initializing them with 0.

If that doesn’t work, I’d be able to review your code tonight, once I’m back home. :smiling_face:

Best,
Charly

1 Like

Hi @hyunshi,

You could use some html to get that effect. See if this is what you are looking for:

def CreateProgressBar(pg_caption, pg_int_percentage, pg_colour, pg_bgcolour):
    pg_int_percentage = str(pg_int_percentage).zfill(2)
    pg_html = f"""<table style="width:50%; border-style: none;">
                        <tr style='font-weight:bold;'>
                            <td style='background-color:{pg_bgcolour};'>{pg_caption}: <span style='accent-color: {pg_colour}; bgcolor: transparent;'>
                                <progress value='{pg_int_percentage}' max='100'>{pg_int_percentage}%</progress> </span>{pg_int_percentage}% 
                            </td>
                        </tr>
                    </table><br>"""
    return pg_html

st.markdown(CreateProgressBar("Positive", 62, "#A5D6A7", "#B2EBF2"), True)
st.markdown(CreateProgressBar("Neutral", 40, "#FFD54F", "#B2EBF2"), True)
st.markdown(CreateProgressBar("Negative", 65, "red", "#B2EBF2"), True)

You can modify the parameters as required.

I used a HTML table, so you can even easily place progress bars side-by-side, by adding more table columns.

Cheers

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.