File size: 1,534 Bytes
da92bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from collections import Counter
import string

def process_text(text, sorting_option):
    # Remove punctuation from the input text
    translator = str.maketrans('', '', string.punctuation)
    text = text.translate(translator)
    
    words = text.split()
    
    # Count word frequencies
    word_counts = Counter(words)
    
    # Sort words based on the selected option
    if sorting_option == 'alphabetically':
        sorted_words = sorted(word_counts.items(), key=lambda x: x[0])
    elif sorting_option == 'by_frequency':
        sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
    else:
        sorted_words = word_counts.items()

    # Get the top 5 words with their frequencies
    top_5_words = sorted_words
    
    # Format the top 5 words and frequencies as an HTML table
    table_html = "<table style='width:100%'><tr><th>Word</th><th>Frequency</th></tr>"
    for word, freq in top_5_words:
        table_html += f"<tr><td>{word}</td><td>{freq}</td></tr>"
    table_html += "</table>"
    
    # Wrap the table in a div with a fixed height and scrolling
    div_with_scroll = f"<div style='height: 200px; overflow-y: scroll;'>{table_html}</div>"
    
    return div_with_scroll

iface = gr.Interface(
    fn=process_text,
    inputs=[gr.Textbox("text", label="Paste Text Here"), 
            gr.Radio(["alphabetically", "by_frequency", "none"], label="Select Sorting Option")],
    outputs=gr.HTML(label="Top 5 Words with Frequencies")
)

iface.launch(share=True)