SEfrenkie 2024-11-18 20:47 采纳率: 0%
浏览 3

python词频统计代码问题在哪儿啊

有没有人帮我看看为什么分完词后,统计词频时是按照单个字符统计的?
运行结果如下图

img

#数据资产管理实践白皮书(6.0版)
import jieba # 使用jieba分词
fileContent = open(r'D:/anacondadata/dataassetguanjiancicidian/数据资产管理实践白皮书(6.0版).txt','r', encoding = "utf-8").read()
words = jieba.lcut_for_search(fileContent)# 分词后返回一个列表
#print(words)
with open('D:\\anacondadata\\dataassetguanjiancicidian\\stopword\\hit_stopwords.txt', 'r', encoding='UTF-8') as files: 
     stopwords = [line.strip() for line in files.readlines()] #加载停用词表
result = ""
for w in words:
    if w not in stopwords and len(w)>1: # 停用词过滤
        if w not in '\n \t \r \f': #去除特殊符号
            result+=w+" "
print(result)
counts = {}
for word in result:
        counts[word] = counts.get(word, 0) + 1
for word, count in counts.items():
 print(f"{word}: {count}")


img

  • 写回答

1条回答 默认 最新

  • 关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    从你的代码和运行结果来看,问题在于你的词频统计部分对单个字符进行了统计。这是因为你遍历了 result 字符串中的每一个字符,然后将它们作为单独的词进行了统计。而 result 字符串中的每个字符(包括空格和标点符号)都被单独计算了。所以,你看到的统计结果中有很多单个字符的出现次数。

    你应该对分词后的列表 words 进行词频统计,而不是对处理后的字符串 result 进行统计。以下是你应该修改的词频统计部分:

    counts = {}
    for word in words:  # 这里改为遍历 words 列表
        if word not in stopwords and len(word)>1:  # 停用词过滤
            counts[word] = counts.get(word, 0) + 1  # 统计词频
    for word, count in counts.items():
        print(f"{word}: {count}")
    

    这样的修改应该能正确地按照单词进行词频统计,而不是按照单个字符进行统计。另外,注意在处理文本数据时,有时候还需要考虑标点符号和特殊字符的处理,你可能需要更精细地处理这些部分,以确保你的词频统计结果符合预期。

    评论

报告相同问题?

问题事件

  • 创建了问题 11月18日