Python 统计词频gui

from tkinter import Tk, Label, Entry, Button, Canvas, Scrollbar
from collections import defaultdict
import matplotlib.pyplot as plt

#统计词频

def count_words(text):
words = text.split()
word_freq = defaultdict(int)
for word in words:
word_freq[word] += 1
return word_freq

#绘制词频图形

def plot_word_freq(word_freq):
plt.bar(word_freq.keys(), word_freq.values())
plt.xlabel(‘Words’)
plt.ylabel(‘Frequency’)
plt.title(‘Word Frequency’)
plt.show()

#创建主窗口

root = Tk()

#创建标签和输入框

label_text = Label(root, text=’请输入文本:’)
entry_text = Entry(root)

#创建按钮

button_count = Button(root, text=’统计词频’, command=lambda: count_words(entry_text.get()))
button_plot = Button(root, text=’绘制图形’, command=lambda: plot_word_freq(count_words(entry_text.get())))

#创建画布和滚动条

canvas = Canvas(root, width=800, height=600)
scrollbar = Scrollbar(root, orient=’vertical’, command=canvas.yview)

#在画布中添加文本标签、输入框、两个按钮
label_text.pack()
entry_text.pack()
button_count.pack()
button_plot.pack()

#将画布和滚动条组合在一起

canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=’right’, fill=’y’)
canvas.pack()

#主循环

root.mainloop()