《沉默的羔羊》之最多单词
【问题描述】
文件"demo.txt"是《沉默的羔羊》中文版内容,请读入文件内容,分词后输出长度大于2且最多的单词。
如果存在多个单词出现频率一致,请输出按照Unicode排序后最大的单词。
注意:要读入的文件已放入当前目录下,源文件中直接读取此文件即可。
import jieba
from collections import Counter
# 打开并读取文件
with open('demo.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba进行分词
words = jieba.lcut(text)
# 过滤掉长度不大于2的词
words = [word for word in words if len(word) > 2]
# 计算每个词的出现次数
word_counts = Counter(words)
# 找出出现次数最多的词
most_common_words = word_counts.most_common()
# 获取出现次数最多的次数
max_count = most_common_words[0][1]
# 获取所有出现次数最多的词
max_count_words = [word for word, count in most_common_words if count == max_count]
# 按照Unicode排序后选择最大的词
max_word = max(max_count_words, key=lambda word: (word.encode('utf-8')))
print(max_word)
文本词频统计 – Hamlet
【问题描述】一篇文章,出现了哪些词?哪些词出现的最多?
请统计hamlet.txt文件中出现的英文单词情况,统计并输出出现最多的5个单词,注意:
(1) 单词不区分大小写,即单词的大小写或组合形式一样;
(2) 请在文本中剔除英文标点符号;
(3) 输出5个单词,每个单词一行;
(4) 输出单词为小写形式。
注意:要读入的文件已放入当前目录下,源文件中直接读取此文件即可。
import re
from collections import Counter
# 打开并读取文件
with open('hamlet.txt', 'r') as f:
text = f.read().lower()
# 移除所有的标点符号
text = re.sub(r'[^\w\s]', '', text)
# 分割文本为单词列表
words = text.split()
# 计算每个单词的出现次数
word_counts = Counter(words)
# 找出出现次数最多的5个单词
most_common_words = word_counts.most_common(5)
# 打印出现次数最多的5个单词
for word, count in most_common_words:
print(word)