ITPub博客

首页 > 应用开发 > Python > 编写一个文本文件的词频统计程序,并输出前N个高频词。

编写一个文本文件的词频统计程序,并输出前N个高频词。

原创 Python 作者:mingtian66 时间:2024-09-19 10:43:22 0 删除 编辑

下面是一个简单的Python程序,用于统计文本文件中的词频,并输出前N个高频词。

python

import collections
import re

def count_word_frequencies(file_path):
    """统计文本文件中的词频"""
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read().lower()  # 读取文件并转换为小写
        words = re.findall(r'\b\w+\b', text)  # 使用正则表达式提取单词

    word_counts = collections.Counter(words)  # 统计单词频率
    return word_counts

def print_top_n_words(word_counts, n):
    """打印前N个高频词"""
    print(f"前 {n} 个高频词:")
    for word, count in word_counts.most_common(n):
        print(f"{word}: {count}")

if __name__ == "__main__":
    file_path = 'text.txt'  # 请将此处替换为你的文本文件路径
    n = 10  # 设置要输出的高频词数量

    word_counts = count_word_frequencies(file_path)
    print_top_n_words(word_counts, n)

代码说明

    count_word_frequencies(file_path):该函数接受一个文件路径作为参数,读取文件内容,使用正则表达式提取单词,统计并返回每个单词的频率。
    print_top_n_words(word_counts, n):该函数接受一个词频统计结果和要输出的高频词数量,打印出前N个高频词。
    主程序:在__main__中指定文件路径和N的值,调用上述函数进行统计和输出。

使用说明

    将上面的代码保存为Python文件,例如word_frequency.py。
    创建一个文本文件(例如text.txt),并在其中写入一些内容。
    运行程序,程序将输出前N个高频词及其出现次数。

确保在运行程序时,文本文件的路径是正确的,并且文件中有内容。你可以根据需要调整N的值以获取不同数量的高频词。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3028147/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    602807