Spaces:
Sleeping
Sleeping
| import re | |
| import gradio as gr | |
| def analyze_word_freq(text): | |
| # 1. 文字全部轉為小寫 (lowercase) | |
| # 2. 用正規表達式擷取 (a-z, A-Z) 字母串 | |
| words = re.findall(r"[a-zA-Z]+", text.lower()) | |
| # 建立詞頻字典 | |
| freq = {} | |
| for w in words: | |
| freq[w] = freq.get(w, 0) + 1 | |
| # 以 (頻率 desc, 單字 asc) 排序 | |
| sorted_freq = sorted(freq.items(), key=lambda x: (-x[1], x[0])) | |
| # 最終輸出格式: 一行一個 "word : count" | |
| # 您可以改成您想要的其他格式 | |
| results = [] | |
| for word, count in sorted_freq: | |
| results.append(f"{word} : {count}") | |
| # 回傳字串, 並用換行符號串起來 | |
| return "\n".join(results) | |
| # 建立 Gradio 的介面 | |
| iface = gr.Interface( | |
| fn=analyze_word_freq, # 主要執行的函式 | |
| inputs="text", # 輸入為一段文字 | |
| outputs="text", # 輸出為一段文字 | |
| title="English Word Frequency Analyzer", | |
| description="Paste or type your article below, then click 'Submit' to see the word-frequency analysis." | |
| ) | |
| # 啟動 Gradio App | |
| if __name__ == "__main__": | |
| iface.launch() | |