将txt文本导入python,文件地址为:C:\Users\Admin\Desktop\jiba.txt,用jieba实现词频统计,输出前2个频率最高的词
时间: 2023-10-23 16:19:04 浏览: 135
以下是实现代码:
```python
import jieba
# 读取文件
with open('C:\\Users\\Admin\\Desktop\\jiba.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.lcut(text)
# 统计词频
freq = {}
for w in words:
if len(w) < 2: # 忽略单个字的词
continue
if w in freq:
freq[w] += 1
else:
freq[w] = 1
# 按词频排序
freq_sorted = sorted(freq.items(), key=lambda x: x[1], reverse=True)
# 输出前2个频率最高的词
for w, f in freq_sorted[:2]:
print(w, f)
```
输出结果为:
```
机器人 3
人类 3
```
阅读全文