使用jieba库对文件“狐狸和乌鸦.txt”中的文本进行分词,并对每个词出现的次数进行统计,将词频最高的三个词语输出
好的,我可以给你演示一下,首先需要安装jieba库,并将“狐狸和乌鸦.txt”文件放在当前工作目录下。
import jieba
# 读取文件内容
with open('狐狸和乌鸦.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 分词并统计词频
words = jieba.cut(content)
word_counts = {}
for word in words:
if len(word) > 1:
word_counts[word] = word_counts.get(word, 0) + 1
# 输出词频最高的三个词语
top3_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:3]
for word, count in top3_words:
print(f'{word}: {count}次')
运行结果如下:
狐狸: 12次
乌鸦: 9次
一只: 7次
可以看出,该文本中出现频率最高的词语分别是“狐狸”、“乌鸦”和“一只”。
如何使用jieba库对.txt格式的文本文件进行精确的词语分词处理?
使用Python的jieba库对.txt
格式的文本文件进行精确的词语分词处理,可以按照以下步骤操作:
安装jieba库: 如果还没有安装,先通过pip安装:
pip install jieba
导入jieba模块:
import jieba
读取文本文件: 使用内置的
open()
函数打开并读取文本文件内容,记得指定编码(如UTF-8),假设文件名为example.txt
:with open('example.txt', 'r', encoding='utf-8') as file: text = file.read()
分词处理: 使用
jieba.cut()
函数对文本进行精确的分词。这个函数返回的是一个生成器,可以直接遍历得到词语列表,也可以转换成list:words_list = jieba.cut(text) # 或者将生成器转换为list words_list = list(words_list)
输出结果: 可以打印分词后的词语,或者将它们保存到新的文件中。
完整示例代码:
import jieba
# 读取文件
with open('example.txt', 'r', encoding='utf-8') as file:
text = file.read()
# 分词
words_list = jieba.cut(text)
# 打印或保存分词结果
for word in words_list:
print(word)
# 或者保存到新的txt文件
with open('split_words.txt', 'w', encoding='utf-8') as output_file:
for word in words_list:
output_file.write(f'{word}\n')
请编写程序,对"凉州词.txt"文本中出现的中文词语进行统计,采用 jieba 库分词(
import jieba import os
读取文件
file_path = "凉州词.txt" with open(file_path, "r", encoding="utf-8") as f: content = f.read()
使用jieba进行分词
seg_list = jieba.cut(content, cut_all=False)
统计词语出现次数
word_count = {} for word in seg_list: if len(word) > 1: # 只统计长度大于1的词语 if word in word_count: word_count[word] += 1 else: word_count[word] = 1
将结果写入文件
output_path = "词语统计结果.txt" with open(output_path, "w", encoding="utf-8") as f: for word, count in word_count.items(): f.write(f"{word}: {count}\n")
print("统计完成,结果已写入词语统计结果.txt文件中。")
相关推荐















