高仿模拟练习,完整编写程序并运行出结果,答案点击按钮展开
从 news.txt 读取整篇英文文章。 1) 将所有字母转为小写; 2) 按空白切分为单词,去掉单词两端标点(.,!?"'); 3) 跳过长度 < 2 的单词; 4) 统计词频并输出出现次数最多的前 10 个单词,每行格式 单词:次数。
# news.txt 示例内容:
# Python is an interpreted language. Python is popular!
# Data science uses Python and data libraries.
import string
with open("news.txt") as f:
text = f.read().lower()
words = text.split()
# 请在下面编写完整程序:去掉标点两端、跳过<2、统计、TOP10输出
freq = {}
for w in words:
# strip 去两端标点
w = w.strip(string.punctuation)
if len(w) < 2:
continue
freq[w] = freq.get(w, 0) + 1
# 按次数降序取前10
top10 = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:10]
for w, n in top10:
{n}")
lower() 统一小写;string.punctuation.strip() 去两端标点;<2 过滤单字母虚词。
字典 d.get+1 计数;sorted(items, key=lambda x:-x[1])[:10] 取 TOP10。
示例结果:python:3, data:2, is:2, an:1, interpreted:1 等。