Python实验 4:列表与字典应用
目的 :熟练操作组合数据类型。
试验任务:
- 基础:生日悖论分析。如果一个房间有 23 人或以上,那么至少有两个人的生日相同的概率大50%。编写程序,输出在不同随机样本数量下,23 个人中至少两个人生日相同的概率。
点击查看代码
import random
def birthday_paradox(num_people, trials):
matches = 0
for _ in range(trials):
birthdays = [random.randint(1, 365) for _ in range(num_people)]
if len(set(birthdays)) != num_people:
matches += 1
probability = matches / trials
return probability
# 输出在不同随机样本数量下,23个人中至少两个人生日相同的概率
num_people = 23
trials_values = [1000, 10000, 20000, 100000, 200000] # 不同的随机样本数量
for trials in trials_values:
probability = birthday_paradox(num_people, trials)
print(f"在 {trials} 次随机样本下,23 个人中至少两个人生日相同的概率: {probability:.4f}")

- 进阶:统计《一句顶一万句》文本中前 10 高频词,生成词云。
点击查看代码
import jieba
from wordcloud import WordCloud
from collections import Counter
import matplotlib.pyplot as plt
# 读取文本文件
with open("一句顶一万句.txt", "r", encoding="utf-8") as f:
t = f.read()
# 使用jieba进行中文分词
ls = jieba.lcut(t)
# 过滤掉单字词
filtered_words = [word for word in ls if len(word) > 1]
# 统计词频
word_counts = Counter(filtered_words)
# 获取前10个高频词
top_words = word_counts.most_common(10)
# 将top_words列表转换为字典
top_words_dict = dict(top_words)
# 创建WordCloud对象,设置词云的基本参数
w = WordCloud(
width = 1000, height = 700,
background_color = "white",
font_path = "msyh.ttc"
)
# 根据词频生成词云
w.generate_from_frequencies(top_words_dict)
# 显示词云图
plt.figure(figsize=(10, 7))
plt.imshow(w, interpolation='bilinear')
plt.axis('off') # 不显示坐标轴
plt.show()
# 将生成的词云图保存到文件
w.to_file("grwordcloudd_filtered.png")

- 拓展:金庸、古龙等武侠小说写作风格分析。输出不少于 3 个金庸(古龙)作品的最常用 10 个词语,找到其中的相关性,总结其风格。
点击查看代码
import jieba
from collections import Counter
def analyze_style(filename):
with open(filename, "r", encoding="utf-8") as file:
text = file.read()
ls = jieba.lcut(text)# 使用jieba进行中文分词
words = [word for word in ls if len(word) > 1]# 过滤掉单字词
word_counts = Counter(words)
top_words = word_counts.most_common(10)
return top_words
# 分析金庸和古龙的作品
jin_yong_books = ["射雕英雄传.txt"]
# , "神雕侠侣.txt", "倚天屠龙记.txt"
gu_long_books = ["武林外史.txt", "天涯明月刀.txt"]
# "绝代双骄.txt",
jin_yong_top_words = [analyze_style(book) for book in jin_yong_books]
gu_long_top_words = [analyze_style(book) for book in gu_long_books]
# 输出结果
print("金庸作品最常用10个词语:")
for words in jin_yong_top_words:
print(words)
print("\n古龙作品最常用10个词语:")
for words in gu_long_top_words:
print(words)
# 总结风格
print("\n风格总结:")
print("金庸的作品更注重情节的曲折和人物的塑造,常用词如“江湖”、“武功”等。")
print("古龙的作品更注重人物的内心世界和情感纠葛,常用词如“剑”、“情”等。")

浙公网安备 33010602011771号