python中文词频怎么做,python中文文本统计词频的步骤

首页 > 教育培训 > 作者:YD1662023-06-20 03:01:09

在 Python 中,可以利用字典进行词频统计。具体做法是,将文本分割成单词,然后使用一个字典记录每个单词出现的次数。以下是一个简单的示例代码:

text = "this is a sample text with several words and some of them repeat several times" # 将文本分割成单词 words = text.split() # 定义一个空字典,用于记录每个单词的出现次数 word_count = {} # 遍历每个单词,统计出现次数 for word in words: if word not in word_count: word_count[word] = 1 else: word_count[word] = 1 # 输出结果 for word, count in word_count.items(): print(f"{word}: {count}")

运行结果如下所示:

this: 1 is: 1 a: 1 sample: 1 text: 1 with: 1 several: 2 words: 1 and: 1 some: 1 of: 1 them: 1 repeat: 1 times: 1

上述代码中,首先将文本分割成单词,然后遍历每个单词,如果单词不在字典中,则将其添加到字典中,并设置出现次数为 1;如果单词已经在字典中,则将其出现次数加 1。最后遍历字典,输出每个单词的出现次数。

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.