文本分词并统计出现次数最高的几个词Python

本文介绍了如何使用Python进行文本数据分析的词频统计。通过读取文本文件,进行分词、去除停用词,最终找出出现次数最多的N个词。

一、问题描述

在做文本数据分析时,经常遇到需要做词频分析,而做词频分析又经常需要统计出现次数最高的几个词,下面代码给出了基于Python的文本数据统计,基本流程为:首先读取一个文本文件,之后进行分词,再去除停用词,最后统计出现次数最多的N个词。

二、Python代码

import jieba
from collections import Counter
############################################
# 功能:获取文本文件内容
# 输入参数
#       filename:待读取的文本文件名
# 返回值
#       txtConts:读取的文本内容
def GetTxtDataFromFile( filename ):
    with open( filename, mode = 'r' ) as fp:
        txtConts = fp.read()
        return txtConts
############################################
# 功能:分词,并去除分词结果中的停用词
# 输入参数
#       txtConts:原始文本
#       stopWord:停用词
# 返回值
#       cutList:去除停用词之后的分词结果
def CutWithStopWord( txtConts, stopWord ):
    cutList = []
    strList = jieba.cut( txtConts )
    
    for word in strList:
        if not( word in stopWord ) and len( word ) > 1:
            
Python 中,可以使用多种方法进行出现次数最多统计。以下是几种常见的方法: #### 使用 `collections.Counter` 类 ```python from collections import Counter text = "apple banana apple cherry banana apple" words = text.split() word_counts = Counter(words) most_common_word = word_counts.most_common(1)[0] print(f"出现次数最多是 '{most_common_word[0]}',出现了 {most_common_word[1]} 次。") ``` 这种方法使用 `collections.Counter` 类,它可以方便地统计可迭代对象中元素的出现次数,`most_common()` 方法可以返回出现次数最多的元素及其次数。 #### 手动统计 ```python text = "apple banana apple cherry banana apple" words = text.split() word_count_dict = {} for word in words: if word in word_count_dict: word_count_dict[word] += 1 else: word_count_dict[word] = 1 max_count = 0 most_common_word = "" for word, count in word_count_dict.items(): if count > max_count: max_count = count most_common_word = word print(f"出现次数最多是 '{most_common_word}',出现了 {max_count} 次。") ``` 此方法手动遍历单列表,使用字典记录每个单的出现次数,然后找出出现次数最多的单。 #### 处理中文文本(使用 `jieba` 库) 对于中文文本,需要使用 `jieba` 库进行分词,因为中文句子中的词语没有像英文那样用空格分隔[^2]。 ```python import jieba from collections import Counter text = "我喜欢编程,编程使我快乐" words = jieba.lcut(text) word_counts = Counter(words) most_common_word = word_counts.most_common(1)[0] print(f"出现次数最多是 '{most_common_word[0]}',出现了 {most_common_word[1]} 次。") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值