目的:创建一个交互界面,而不是直接从控制台中输入数据,输入英文语句之后,在界面中展示出统计的结果,并将统计的结果保存在指定的文件中。
代码展示:
# coding:UTF-8
import tkinter as tk
#打开文件
root=tk.Tk()
root.title('单词分析器')
root.geometry('700x700')
#设置标签
label1=tk.Label(root,text='输入日期,以空格分隔:',font=('楷书',12),background='white')
label1.place(x=45,y=15)
def getData():
str2=(text.get("0.0", "end")).lower()
str3=[]
for i in '"".,;/?:!@#$%^&*()_-=+][{}`~\|1234567890':
str2 = str2.replace(i, " ")
str3 = str2.split()
dict1 = {}
for i in str3:
dict1[i] = str3.count(i)
list1 = sorted(dict1.items(), key=lambda x: x[1], reverse=True)
try:
f = open('test2.txt', mode='w', encoding='UTF-8')
for i in range(0, len(list1)):
for j in range(0, 2):
if (j == 0):
f.write("单词'" + str(list1[i][j]) + "'" + "的个数为:")
if (j == 1):
f.write(str(list1[i][j]) + "个 \n")
f.close()
except FileNotFoundError:
print("打开文件错误,请重新检查文件")
else:
print("\n文件写入保存成功!")
putData()
def putData():
fp = open('test2.txt', mode='r', encoding='UTF-8')
label1 = tk.Label(root, text='该英文语句的统计结果如下:', font=('楷书', 12),background='white')
label1.place(x=635, y=15)
str1=fp.readlines()
text1 = tk.Text(root,font=12)
text1.place(x=650, y=46, width=400, height=400)
for i in str1:
text1.insert(index=tk.END,chars=i)
def delete_text():
text.delete(0.0,tk.END)
# 设置多行文本框
text=tk.Text(root,font=('宋体',15))
text.place(x=170,y=46,width=400,height=400)
button1=tk.Button(root,text="统计",command=getData,font=15)
button1.place(x=200,y=480,width=50,height=50)
button2=tk.Button(root,text="清空",command=delete_text,font=15)
button2.place(x=330,y=480,width=50,height=50)
button3=tk.Button(root,text="退出",command=root.quit,font=15)
button3.place(x=450,y=480,width=50,height=50)
root.mainloop()
结果展示:
直接输入一整本英文文章:
输入英文语句:
保存的结果在文件中的形式: