本文介绍利用python实现了简单的词频统计程序,其中涉及了简单的正则表达式的使用和python可视化模块tkinter的使用。完成了选择任意的文件,然后统计其中的单词的出现频度并以列表的形式展现出来。最后连接数据库并将所得的结果写入数据库。

一,首先是简单的词频统计

利用文件名读取文件,然后调用remove_punctuation()函数去除其中的杂乱的字符,实现只有英文的字符。然后将得到的字符串转化为字典,单词作为索引,次数作为值,一遍循环以后实现了建立词频统计,然后将结果写入了文件中,用于验证。

    wordDict = {}with open(filenamevar) as file:content = file.read()# remove the character which is not in a-zA-Zcontent = remove_punctuation(content)# covert the str to the lower statementcontent = content.lower()wordList = sorted(list(content.split()))for word in wordList:if word not in wordDict:wordDict[word] = 1else:wordDict[word] = wordDict[word] + 1file.close()with open('out.txt', 'w') as file2:for x, y in wordDict.items():file2.write(x + ' ' + str(y) + '\n')

以下是remove_punctuation()函数部分,利用简单的正则表达式,用空格替换原来的除英文意外的字符,返回目标字符串:

def remove_punctuation(line):rule = re.compile(r"[^a-zA-Z]")line = rule.sub(' ', line)return line

二,tkinter的使用

利用tkinter构建简单的客户端:

root = tk.Tk()
entryvar = tk.StringVar()  # 路径
root.geometry('600x400+400+200')
# var.set("请选择你要打开的文件")
root.title("统计词频")# define the frame
frame = tk.Frame(root)
frame2 = tk.Frame(root)frame2.place(x=100, y=30, width=300, height=175)
# label = tk.Label(frame2, textvariable = var).pack(side = tk.LEFT)
Entryvar = tk.Entry(frame2, textvariable=entryvar, width=20)
Entryvar.pack(side=tk.LEFT)
# print((type(Entryvar)))
button = tk.Button(frame2, text="读入文件", command=getFile).pack(side=tk.LEFT)
button2 = tk.Button(frame2, text="统计", command=wordResult).pack(side=tk.LEFT)
button3 = tk.Button(frame2, text="插入数据库", command=pyDatebase).pack(side=tk.LEFT)# 表格
frame.place(x=400, y=30, width=170, height=330)
scrollBar = tk.Scrollbar(frame)
scrollBar.pack(side=tk.RIGHT, fill=tk.Y)tree = Treeview(frame, columns=('c1', 'c2'), show="headings", yscrollcommand=scrollBar.set)
tree.column('c1', width=90, anchor='center')
tree.column('c2', width=70, anchor='center')
tree.heading('c1', text='单词')
tree.heading('c2', text='出现次数')
tree.pack(side=tk.LEFT, fill=tk.Y)
scrollBar.config(command=tree.yview)root.mainloop()

三,数据库连接

利用pymysql连接工具连接数据库,向数据库中插入数据。

def pyDatebase():connect = pymysql.Connect(host='localhost', port=3306, user='root', passwd='123456', db='python', charset='utf8')# 获取游标cursor = connect.cursor()#删除原数据sql_delete = "delete from test;"cursor.execute(sql_delete)# 插入数据sql_insert = "INSERT INTO test (word, number) VALUES ( '%s', '%s')"for x, y in wordDict.items():date = x, ycursor.execute(sql_insert % date)connect.commit()print('成功插入条数据')

最终测试结果如下:

结果反思:

首先在tkinter的使用过程中,最开始是直接通过askopenfilename()这个函数去获取对话框中打开的文件的文件名,然后想要利用这个文件名进行一系列的操作,但是,经过不断的测试发现,利用button()的command属性调用的函数,不会再mainloop()循环以内就返回值,也就是说,再可视化的循环内是获取不到filename的,这也就导致了无法去获取文件名,无法进一步进行操作,然后在搜寻资料发现了要向在mainloop()循环内获得这个值,那么就必须得使用tkinter的内部String变量的方法StringVar并进行动态赋值,才能实现文件名的获取,也才能实现后续的一系列操作。

由此可见,对一个已调用模块的熟悉程度也就注定了自己在这个模块的使用的过程中会有多大的返工。

附源码如下:

import re
import tkinter as tk
import pymysql.cursors
import tkinter.filedialog
from tkinter.ttk import TreeviewwordDict = {}def pyDatebase():connect = pymysql.Connect(host='localhost', port=3306, user='root', passwd='123456', db='python', charset='utf8')# 获取游标cursor = connect.cursor()#删除原数据sql_delete = "delete from test;"cursor.execute(sql_delete)# 插入数据sql_insert = "INSERT INTO test (word, number) VALUES ( '%s', '%s')"for x, y in wordDict.items():date = x, ycursor.execute(sql_insert % date)connect.commit()print('成功插入条数据')def remove_punctuation(line):rule = re.compile(r"[^a-zA-Z]")line = rule.sub(' ', line)return linedef wordResult():filenamevar = Entryvar.get()with open(filenamevar) as file:content = file.read()# remove the character which is not in a-zA-Zcontent = remove_punctuation(content)# covert the str to the lower statementcontent = content.lower()wordList = sorted(list(content.split()))for word in wordList:if word not in wordDict:wordDict[word] = 1else:wordDict[word] = wordDict[word] + 1file.close()with open('out.txt', 'w') as file2:for x, y in wordDict.items():file2.write(x + ' ' + str(y) + '\n')for x, y in wordDict.items():tree.insert('', 'end', value=(x, y))# 获取文件的路径
def getFile():global filenamefilename = tk.filedialog.askopenfilename()entryvar.set(filename)root = tk.Tk()
entryvar = tk.StringVar()  # 路径
root.geometry('600x400+400+200')
# var.set("请选择你要打开的文件")
root.title("统计词频")# define the frame
frame = tk.Frame(root)
frame2 = tk.Frame(root)frame2.place(x=100, y=30, width=300, height=175)
# label = tk.Label(frame2, textvariable = var).pack(side = tk.LEFT)
Entryvar = tk.Entry(frame2, textvariable=entryvar, width=20)
Entryvar.pack(side=tk.LEFT)
# print((type(Entryvar)))
button = tk.Button(frame2, text="读入文件", command=getFile).pack(side=tk.LEFT)
button2 = tk.Button(frame2, text="统计", command=wordResult).pack(side=tk.LEFT)
button3 = tk.Button(frame2, text="插入数据库", command=pyDatebase).pack(side=tk.LEFT)# 表格
frame.place(x=400, y=30, width=170, height=330)
scrollBar = tk.Scrollbar(frame)
scrollBar.pack(side=tk.RIGHT, fill=tk.Y)tree = Treeview(frame, columns=('c1', 'c2'), show="headings", yscrollcommand=scrollBar.set)
tree.column('c1', width=90, anchor='center')
tree.column('c2', width=70, anchor='center')
tree.heading('c1', text='单词')
tree.heading('c2', text='出现次数')
tree.pack(side=tk.LEFT, fill=tk.Y)
scrollBar.config(command=tree.yview)root.mainloop()

python词频统计GUI(thinter)相关推荐

  1. python词频统计(word ——> excel,含去重)

    word资料处理 -------> 存入excel 精简地从word文档读取资料,分析后传入excel文档. 不是txt!因为我的电脑是mac,针对txt的乱码问题解决不了. 主要操作的思维导图 ...

  2. python 词频统计,分词笔记

    Python的中文分词库有很多,常见的有: jieba(结巴分词) THULAC(清华大学自然语言处理与社会人文计算实验室) pkuseg(北京大学语言计算与机器学习研究组) SnowNLP pynl ...

  3. python词频统计代码_python统计词频

    一.程序分析 (1)将文件读入缓冲区(dst指文本文件存放路径,设置成形参,也可以不设,具体到函数里设置) def process_file(dst): # 读文件到缓冲区try: # 打开文件 tx ...

  4. python词频统计完整步骤_Python中文文本分词、词频统计、词云绘制

    本文主要从中文文本分词.词频统计.词云绘制方面介绍Python中文文本分词的使用.会使用到的中文文本处理包包括:wordcloud,jieba,re(正则表达式),collections. 1 准备工 ...

  5. python词频统计西游记_实例10-文本词频统计.pdf

    Python语言程序设计 实例10: 文本词频统计 嵩 天 北京理工大学 "文本词频统计"问题分析 CC BY-NC-SA 4.0 嵩天 问题分析 文本词频统计 - 需求 :一篇文 ...

  6. python词频统计时、文件放哪里_初学python,词频统计小实验

    最近突然对python感兴趣,就学了起来.我可怜的计算机基础只有VB,而且学的时候这门课还特别水,仅仅了解了语法,考试基本上是背题过的. 现在自学python还是比较吃力.今天捣鼓了一下午,搞出了一个 ...

  7. python词频统计实验报告_Python实验报告八

    安徽工程大学Python程序设计 班级:物流191 姓名:汤振宇 学号:319050108 成绩: 日期:2020/06/04 指导老师:修宇 [实验目的] : 掌握读写文本文件或 CSV 文件,进而 ...

  8. python词频统计完整步骤_python实现词频统计(wordcount)函数

    作为字典(key-value)的经典应用题目,单词统计几乎出现在每一种语言键值对学习后的必练题目,主要需求: 写一个函数wordcount统计一篇文章的每个单词出现的次数(词频统计).统计完成后,对该 ...

  9. Python词频统计之密信约定进攻时间

    问题 假设你是小蔡,你和小徐同学一起穿越到了抗战时期,分别成为了八路军华北根据地A地和B地的联络员.此时,两地的八路军部队准备发动协同进攻,给予日寇重重一击.由于某些原因无法亲自送信,为了约定进攻时间 ...

最新文章

  1. 如何配置php的ip地址吗,如何手动配置IP地址及防火墙设置
  2. linux查看网卡传输,Linux下查看网卡实时流量工具
  3. CSS使用display:incline与float:left的区别:脱离文档流 参差不齐
  4. python 下载拉钩教育AES加密视频
  5. 源码|详解分布式事务之 Seata-Client 原理及流程
  6. mysql 最短路经_poj 3613 Cow Relays 经L边的最短路 | 学步园
  7. django-cookie与session的应用场景
  8. 336 Palindrome Pairs 回文对
  9. 无线通信设备安装工程概预算编制_深圳电气安装造价培训-如何计算电气设备安装工程预算定额?...
  10. CIKM 2020 | FANG:利用社会语境及其图表示进行假新闻检测
  11. uniapp H5 seo 百度自动收录(html通用代码)
  12. 全球与中国糖粉市场深度研究分析报告
  13. 基于声学模型共享的零资源韩语识别系统
  14. Arcgis中地理坐标系转投影坐标系(自定义地理坐标转换)
  15. DOS重装win7系统
  16. iOS-TZImagePickerController获取相册照片、视频 (Swift代码)
  17. 【无标题】五大免费使用的在线客服系统盘点
  18. DFS(深度优先搜索)学习笔记(C语言版本)
  19. nginx php mysql 配置及启动
  20. 我的2021年总结,从大专生到本科生。

热门文章

  1. AI留给教练的时间已经不多了
  2. pandas筛选数据_2_条件筛选
  3. Python之浅谈exec函数
  4. linux cut命令
  5. 【python】Python性能鸡汤
  6. 开源项目SMSS发开指南(四)——SSL/TLS加密通信详解
  7. VC获取系统空闲时间
  8. 使用JAVA调用U盾进行客户认证的total solution
  9. 分布式系统脑裂现象、Lease机制介绍
  10. Mp3Player VS Diskman(2)