Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import gradio as gr
|
| 3 |
+
|
| 4 |
+
def analyze_word_freq(text):
|
| 5 |
+
# 1. 文字全部轉為小寫 (lowercase)
|
| 6 |
+
# 2. 用正規表達式擷取 (a-z, A-Z) 字母串
|
| 7 |
+
words = re.findall(r"[a-zA-Z]+", text.lower())
|
| 8 |
+
|
| 9 |
+
# 建立詞頻字典
|
| 10 |
+
freq = {}
|
| 11 |
+
for w in words:
|
| 12 |
+
freq[w] = freq.get(w, 0) + 1
|
| 13 |
+
|
| 14 |
+
# 以 (頻率 desc, 單字 asc) 排序
|
| 15 |
+
sorted_freq = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
|
| 16 |
+
|
| 17 |
+
# 最終輸出格式: 一行一個 "word : count"
|
| 18 |
+
# 您可以改成您想要的其他格式
|
| 19 |
+
results = []
|
| 20 |
+
for word, count in sorted_freq:
|
| 21 |
+
results.append(f"{word} : {count}")
|
| 22 |
+
|
| 23 |
+
# 回傳字串, 並用換行符號串起來
|
| 24 |
+
return "\n".join(results)
|
| 25 |
+
|
| 26 |
+
# 建立 Gradio 的介面
|
| 27 |
+
iface = gr.Interface(
|
| 28 |
+
fn=analyze_word_freq, # 主要執行的函式
|
| 29 |
+
inputs="text", # 輸入為一段文字
|
| 30 |
+
outputs="text", # 輸出為一段文字
|
| 31 |
+
title="English Word Frequency Analyzer",
|
| 32 |
+
description="Paste or type your article below, then click 'Submit' to see the word-frequency analysis."
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# 啟動 Gradio App
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
iface.launch()
|