在nlp_lab下,用jieba库编写Python代码,从给定的中文文本文件中统计出最常出现的三个单词
时间: 2024-09-06 19:02:24 浏览: 24
在NLP Lab环境中,你可以使用jieba库对中文文本进行分词并计算词频。以下是如何实现这个功能的Python代码:
```python
# 引用[1]
from collections import Counter
import jieba
import re
# 引用[2]
def top_three_words(file_path):
# 读取文本文件
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
# 清洗文本,只保留中文字符
cleaned_text = re.sub(r'[^\u4e00-\u9fa5]', '', text)
# 使用jieba进行分词
seg_list = jieba.lcut(cleaned_text) # 使用精确模式分词
# 计算词频
word_counts = Counter(seg_list)
# 获取最常见的三个词及其频率
most_common_words = word_counts.most_common(3)
return most_common_words
file_path = "your_chinese_text_file.txt" # 替换为你的中文文本文件路径
top_words = top_three_words(file_path)
for word, freq in top_words:
print(f"{word}: {freq}")
```
在这个代码中,我们首先打开文本文件,清洗文本以保留中文字符,然后使用`jieba.lcut()`函数进行精确模式分词,接着使用`Counter`计算词频,并最后返回出现次数最多的前三个词。