python代码简单实现一个词频统计
来源:互联网 发布:关于走心的文案 知乎 编辑:程序博客网 时间:2024/05/19 16:38
python代码简单实现一个词频统计
path = 'C://Users/DELL/Desktop/Text.txt'with open(path, 'r') as text: words = text.read().split() print(words) for word in words: print('{}-{}times'.format(word, words.count(word)))
import string #引入string模块path = 'C://Users/DELL/Desktop/Text.txt'with open(path,'r') as text: words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] #去掉连在一起的标点符号,大写单词转小写 words_index = set(words) #转换成集合,自动去掉重复元素 counts_dict = {index:words.count(index) for index in words_index} #单词为key,出现频率为value的字典for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True): print('{}--{} times'.format(word, counts_dict[word])) # 打印整理后函数
知识点:
Mac用户使用open函数:
Open('/Users/DELL/Desktop/Walden.txt')
Windows用户使用open函数:
Open('C://Users/DELL/Desktop/Walden.txt')
列表:
列表解析方式放入元素(耗时短,效率高)
普通写法:
a = []
for i in range(1, 11):
a.append(i)
列表解析:
a = [i for i in range(1,11)]
.lower()消除大写
.strip() 移除字符串头尾指定的字符(默认为空格)
sting模块一些有用的字符串常量
string.digits:数字 0 - 9 的字符串
string.letters:所有字母(大写和小写)的字符串
string.lowercase:所有小写字母的字符串
string.printable:所有可打印字符的字符串
string.punctuation:所有标点的字符串
string.uppercase:所有大写字母的字符串
Sorted()函数:按照长短、大小、英文字母顺序给列表中元素排序(Reverse:默认参数reverse可以使列表按逆序整理)
Sorted(num_list,reverse = true)
Key=lambda x:counts_dict[x]: lambda表达式,暂理解为以字典中的值为排序参数
阅读全文
0 0
- python代码简单实现一个词频统计
- Python简单词频统计以及格式合并实现
- python--10行代码搞定词频统计
- 一个简单的词频分析统计程序
- Java简单实现汉语词频统计
- Python实现中文小说词频统计
- 使用Python+NLTK实现英文单词词频统计
- 统计文章词频(python实现)
- 使用Python+NLTK实现英文单词词频统计
- Java实现的一个词频统计程序
- Java实现的一个词频统计程序
- 英文单词词频统计代码
- python 统计词频
- python统计汉字词频
- python 统计词频
- python统计文档词频
- Python新闻联播词频统计
- python词频统计
- 介绍多张图片压缩转Bas64速度优化问题
- ssm整合
- Demo(动态数组的添加输出子类继承的排序反转)
- CI AR模型
- CodeIgniter框架源码学习之安全类--Security.php
- python代码简单实现一个词频统计
- Window下安装配置PyOpenGL
- 2017多校训练第10场-Schedule(贪心+二分)
- linux学习笔记(9)
- Chilkat.NET.Components.for.NET.4.0.
- 4.S5PV210中断相关寄存器详解
- 网页JS蜂巢特效
- 关于CSS如果绘制三角形
- CI Model