Python统计词频
写在前面:
前几天的课堂作业有一项是使用jieba库进行中文分词,当时的代码是参考的网上的,自己也没具体去看,趁着空闲我就重新阅读一下代码。
源码:
import jieba txt = open("房产.csv", "r", encoding='utf-8').read() words = jieba.lcut(txt) # 使用精确模式对文本进行分词 counts = {} # 通过键值对的形式存储词语及其出现的次数 for word in words: if len(word) == 1: # 单个词语不计算在内 continue else: counts[word] = counts.get(word, 0) + 1 # 遍历所有词语,每出现一次其对应的值加 1 items = list(counts.items()) # 将键值对转换成列表 items.sort(key=lambda x: x[1], reverse=True) # 根据词语出现的次数进行从大到小排序 for i in range(1000): word, count = items[i] import pymysql db = pymysql.connect(host="localhost", user="root", password="156132", database="cloud1", charset="utf8mb4") cursor = db.cursor() sql = "insert into fangchan(word,count) values ('" + str(word) + "','" + str( count) + "')" try: cursor.execute(sql) db.commit() # print(school_shengfen + "\t" + school_name + "添加成功") except: print("插入出错") db.rollback() print("{0:<5}{1:>5}".format(word, count))
总结:
1.用open方法打开csv文件,进行内容读取。
2.counts = {},首先定义一个字典,用来存储分词以及出现的次数。
3.注意:访问字典的方式:counts[word] = counts.get(word,0)+1
get方法是根据索引值Word查找,如果没有找到次数就返回默认值0,反之加一,来达到统计词频的目的。
4.list方法是转换成为键值对
5.排序直接调用方法sort