用python代码实现对一个中文文档的词频统计,即统计每个词出现的次数,并实现次数的由大到小排序
时间: 2023-06-12 10:03:28 浏览: 104
以下是Python代码实现中文文档的词频统计和排序的方法:
```python
import jieba
from collections import Counter
# 读取中文文档
with open('chinese_document.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = list(jieba.cut(text))
# 统计词频
word_count = Counter(words)
# 次数由大到小排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_count:
print(word, count)
```
其中,`jieba` 库用于中文分词,`Counter` 类用于统计词频,`sorted` 函数用于排序。在运行代码之前,需要先安装 `jieba` 库。
相关问题
用python代码实现对去停用词的文档进行词频统计,即统计每个词出现的次数,并实现次数的由大到小排序
可以使用Python中的nltk库来进行去停用词和词频统计。以下是一个简单的示例代码:
```python
import nltk
from nltk.corpus import stopwords
from collections import Counter
# 读取文本并分词
with open('example.txt', 'r') as f:
text = f.read()
tokens = nltk.word_tokenize(text)
# 去停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
# 统计词频
word_count = Counter(filtered_tokens)
# 按词频由大到小排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_count:
print(word, count)
```
其中,`example.txt`是要进行词频统计的文本文件。首先通过`nltk.word_tokenize()`函数进行分词,然后使用NLTK库中提供的英文停用词集合去除停用词。接着使用Python的`collections.Counter()`函数统计词频,最后使用Python的`sorted()`函数按词频由大到小排序。
用python代码实现对去停用词的文档进行词频统计,即统计每个词出现的次数。
可以使用 Python 中的 nltk 库来实现去停用词的文档进行词频统计。以下是示例代码:
```python
import nltk
from nltk.corpus import stopwords
from collections import Counter
# 读入文本文件
with open('example.txt', 'r', encoding='utf-8') as f:
text = f.read().lower() # 转成小写
# 分词
words = nltk.word_tokenize(text)
# 去停用词
stop_words = set(stopwords.words('english')) # 英文停用词表
filtered_words = [w for w in words if not w in stop_words]
# 统计词频
word_freq = Counter(filtered_words)
# 输出结果
print(word_freq.most_common(10)) # 显示出现频率最高的前10个词
```
其中,example.txt 是要进行词频统计的文本文件,可以替换成你自己的文本文件名。输出的结果是出现频率最高的前10个词及其出现次数,可根据需要进行调整。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)