对txt文件进行词频统计
时间: 2023-09-29 16:10:58 浏览: 45
可以使用Python来对txt文件进行词频统计,具体步骤如下:
1. 读取txt文件内容:
```python
with open('file.txt', 'r', encoding='utf-8') as f:
text = f.read()
```
2. 对文本进行分词:
```python
import jieba
words = jieba.lcut(text)
```
需要先安装jieba库,可以使用pip命令进行安装:
```
pip install jieba
```
3. 统计词频:
```python
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
```
4. 对词频进行排序:
```python
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
```
最后,可以将结果输出或保存到文件中:
```python
for word, count in sorted_word_count:
print(word, count)
```
相关问题
根据关键词txt文件,对另一个txt文件进行词频统计并得出词频矩阵
你好,根据你的问题,我可以回答。对于关键词txt文件,可以使用Python编程语言中的Counter模块进行词频统计。具体步骤是:首先读取关键词txt文件和待统计txt文件,然后将待统计txt文件中的文本分词,再使用Counter模块统计每个词出现的次数,最后将结果输出为词频矩阵。希望我的回答能够帮助到你。
python对txt文件进行评论词频统计和词云图可视化
好的,以下是Python对txt文件进行评论词频统计和词云图可视化的代码:
```
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取txt文件
with open('comments.txt', 'r', encoding='utf-8') as f:
comments = f.read()
# 使用jieba分词
words = jieba.cut(comments)
# 统计词频
word_counts = Counter(words)
# 生成词云图
wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
wc.generate_from_frequencies(word_counts)
# 显示词云图
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
其中,`jieba`模块用于中文分词,`collections`模块用于统计词频,`wordcloud`模块用于生成词云图,`matplotlib`库用于显示词云图。
需要将要统计的评论保存为`comments.txt`文件放在与代码同一个目录下。如果需要更改词云图的字体、大小、背景颜色等属性,可以在`WordCloud`类的构造函数中进行修改。运行代码后,即可生成词云图并在窗口中显示。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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://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)