使用Python计数文件中的单词频率
本教程向您展示了如何通过使用Python分析单词频率快速确定文档的主要主题。 手动计数单词的发生是乏味的。这种自动化方法简化了过程。
>>我们将使用一个示例文本文件test.txt
(下载它,但不要窥视!)来说明。 目的是根据单词频率猜测教程的主题。
了解正则表达式
这个过程使用正则表达式(REGEX)。 如果不熟悉,则正则是一个字符序列,定义搜索模式的字符串匹配模式(例如“查找和替换”)。 要深入研究,请参阅专用的正则教程。
>构建程序
-
>读取文件:该程序首先将文本文件读取到字符串:
开始document_text = open('test.txt', 'r') text_string = document_text.read().lower()
登录后复制 -
正则表达式:一个正则表达式过滤单词3至15个字符:
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
登录后复制 -
单词频率:词典跟踪单词频率:
frequency = {} for word in match_pattern: count = frequency.get(word, 0) frequency[word] = count + 1
登录后复制 -
然后
完成程序
frequency_list = frequency.keys() for word in frequency_list: print(word, frequency[word])
登录后复制
这是合并的python代码:
>运行此功能将输出一个单词频率列表。 最常见的单词暗示了原始教程的主题。
import re frequency = {} document_text = open('test.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word, 0) frequency[word] = count + 1 frequency_list = frequency.keys() for word in frequency_list: print(word, frequency[word])
>处理较大的文本文件
对于较大的文件,对频率字典进行排序简化了查找最常见的单词:
这将输出一个排序的列表,最常见的单词首先出现。>
import re frequency = {} document_text = open('dracula.txt', 'r') # Example: dracula.txt text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word, 0) frequency[word] = count + 1 most_frequent = dict(sorted(frequency.items(), key=lambda elem: elem[1], reverse=True)) most_frequent_count = most_frequent.keys() for word in most_frequent_count: print(word, most_frequent[word])
不包括常用词
使用黑名单:
import re frequency = {} document_text = open('dracula.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) blacklisted = ['the', 'and', 'for', 'that', 'which'] for word in match_pattern: if word not in blacklisted: count = frequency.get(word, 0) frequency[word] = count + 1 most_frequent = dict(sorted(frequency.items(), key=lambda elem: elem[1], reverse=True)) most_frequent_count = most_frequent.keys() for word in most_frequent_count: print(word, most_frequent[word])
以上是使用Python计数文件中的单词频率的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
