首页 > 后端开发 > Python教程 > 使用Python计数文件中的单词频率

使用Python计数文件中的单词频率

Jennifer Aniston
发布: 2025-03-06 11:59:11
原创
667 人浏览过

本教程向您展示了如何通过使用Python分析单词频率快速确定文档的主要主题。 手动计数单词的发生是乏味的。这种自动化方法简化了过程。

>

>我们将使用一个示例文本文件test.txt(下载它,但不要窥视!)来说明。 目的是根据单词频率猜测教程的主题。

了解正则表达式

这个过程使用正则表达式(REGEX)。 如果不熟悉,则正则是一个字符序列,定义搜索模式的字符串匹配模式(例如“查找和替换”)。 要深入研究,请参阅专用的正则教程。

>

构建程序

  1. >读取文件:该程序首先将文本文件读取到字符串:

    开始
    document_text = open('test.txt', 'r')
    text_string = document_text.read().lower()
    登录后复制
  2. 正则表达式:一个正则表达式过滤单词3至15个字符:

    match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
    登录后复制
  3. 单词频率:词典跟踪单词频率:

    frequency = {}
    for word in match_pattern:
        count = frequency.get(word, 0)
        frequency[word] = count + 1
    登录后复制
  4. 然后

    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])
登录后复制

>处理较大的文本文件Counting Word Frequency in a File Using Python

对于较大的文件,对频率字典进行排序简化了查找最常见的单词:

这将输出一个排序的列表,最常见的单词首先出现。

>

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])
登录后复制

不包括常用词Counting Word Frequency in a File Using Python

使用黑名单: 这提供了更为专注的分析。

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脚本提供了一种可靠的方法,用于分析文本并根据单词频率识别关键主题。 请记住适应黑名单和单词长度标准以满足您的特定需求。

以上是使用Python计数文件中的单词频率的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板