Chat GPT编程入门:Python_词频统计

该代码段展示了一种利用Python的jieba库进行文本分词,然后过滤掉长度小于2的词语,统计词频并输出前10个高频词的方法。它读取GBK编码的文件,对内容进行处理,并以冒号连接词与词频的形式显示结果。
摘要由CSDN通过智能技术生成

要求:统计文件中出现词频最多的前10个长度不小于2个字符的词语,将词语及其出现的词频数按照词频数递减排序后显示在屏幕上,每行显示一个词语,用英语冒号连接词语及词频。示例如:我们:5

直接扔给Chat GPT,根据反馈结果微调,得到:

import jieba
from collections import Counter

def count_top_words(file_path):
    # Read the file with the appropriate encoding
    with open(file_path, 'r', encoding='gbk') as file:
        text = file.read()

    # Perform word segmentation using jieba
    words = jieba.lcut(text)

    # Filter out words with a length less than 2 characters
    words = [word for word in words if len(word) >= 2]

    # Count the frequencies of the words
    word_freq = Counter(words)

    # Get the top 10 most frequent words
    top_words = word_freq.most_common(10)

    # Display the words and frequencies
    for word, freq in top_words:
        print(f"{word}:{freq}")

# Provide the path to your file
file_path = 'path/to/your/file.txt'

# Call the function to count top words
count_top_words(file_path)

用时5min,未来已来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值