25级第四次实验报告
| 2025010089 | 1 |
| 2025010090 | 1 |
| 2025010091 | 1 |
| 2025010092 | 1 |
| 2025010093 | 1 |
| 2025010094 | 1 |
| 2025010095 | 1 |
| 2025010096 | 1 |
| 2025010097 | 1 |
| 2025010098 | 1 |
| 2025010099 | 1 |
| 2025010100 | 1 |
| 2025010101 | 1 |
| 2025010102 | 1 |
| 2025010103 | 1 |
| 2025010104 | 1 |
| 2025010105 | |
| 2025010106 | |
| 2025010107 | 1 |
| 2025010108 | |
| 2025010109 | 1 |
| 2025010110 | |
| 2025010112 | 1 |
| 2025010113 | 1 |
| 2025010114 | 1 |
| 2025010115 | 1 |
| 2025010117 | 1 |
| 2025010118 | 1 |
| 2025010119 | 1 |
| 2025010120 | 1 |
| 2025010121 | 1 |
| 2025010122 | 1 |
| 2025010124 | 1 |
| 2025010125 | 1 |
| 2025010126 | |
| 2025010127 | 1 |
| 2025010128 | 1 |
| 2025010130 | 1 |
| 2025010131 | 1 |
| 2025010132 | 1 |
2025010089张静文
转换账单罗马数字为中文
# 账单数字转中文大写 def num2chinese(n): digit = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'] unit = ['','拾','佰','仟','万','拾','佰','仟','亿'] s = str(n) res, zero = '', False for i, c in enumerate(s): num = int(c) pos = len(s)-i-1 if num != 0: if zero: res += digit[0] res += digit[num] + unit[pos] zero = False else: if pos == 4: res += '万' zero = False else: zero = True return res # ———— 在这里改你的账单数字 ———— if __name__ == '__main__': money = 9999 # 把这里改成你的数字 print(num2chinese(money))

2025010090殷慧湘
# 输入
stu_id = input("请输入学号:").strip()
if len(stu_id) == 10 and stu_id.startswith("2025010") and stu_id[7:].isdigit():
print("✅ 学号格式正确")
else:
print("❌ 学号格式错误,正确格式:2025010xxx")

2025030091张译心
物理题单位中文转英文
def unit_convert(text): # 先去掉多余空格,方便匹配 text = text.replace(" ", "").replace(" ", "") # 长单位词优先,避免被短词提前替换 dic = { "米每秒": "m/s", "千米每小时": "km/h", "米": "m", "千米": "km", "厘米": "cm", "毫米": "mm", "秒": "s", "分钟": "min", "小时": "h", "千克": "kg", "克": "g", "摄氏度": "℃", "牛顿": "N", "帕斯卡": "Pa", "焦耳": "J", "瓦特": "W", "立方米": "m³", "升": "L" } for cn, en in dic.items(): text = text.replace(cn, en) return text # 输入并转换 ques = input("粘贴物理题:") result = unit_convert(ques) print("转换后:", result)

2025010092朱翔鸽
绘制月牙图
import turtle as t t.screensize(400,400,'black') t.shape('turtle') t.turtlesize(3,3,3) t.color('green') t.pu() t.dot(100,'silver') t.fd(20) t.dot(90,'black') t.hideturtle() # 隐藏小乌龟 t.done()

2025010093 惠盾
import tkinter as tk import random # 创建主窗口 root = tk.Tk() root.title("简易弹球游戏") root.geometry("600x500") root.resizable(False, False) # 画布 canvas = tk.Canvas(root, width=600, height=500, bg="#000000") canvas.pack() # 挡板参数 paddle_width = 100 paddle_height = 15 paddle_x = 250 paddle_y = 460 paddle = canvas.create_rectangle( paddle_x, paddle_y, paddle_x + paddle_width, paddle_y + paddle_height, fill="#00BFFF" ) # 小球参数 ball_r = 12 ball_x = 300 ball_y = 200 speed_x = random.choice([-3, 3]) speed_y = 2 ball = canvas.create_oval( ball_x - ball_r, ball_y - ball_r, ball_x + ball_r, ball_y + ball_r, fill="#FF4444" ) # 分数 score = 0 score_text = canvas.create_text(60, 30, text=f"分数:{score}", fill="white", font=("微软雅黑", 16)) # 左移挡板 def move_left(event): global paddle_x if paddle_x > 0: paddle_x -= 7 canvas.coords(paddle, paddle_x, paddle_y, paddle_x + paddle_width, paddle_y + paddle_height) # 右移挡板 def move_right(event): global paddle_x if paddle_x < 600 - paddle_width: paddle_x += 7 canvas.coords(paddle, paddle_x, paddle_y, paddle_x + paddle_width, paddle_y + paddle_height) # 绑定方向键 root.bind("<Left>", move_left) root.bind("<Right>", move_right) # 游戏主逻辑 def game_loop(): global ball_x, ball_y, speed_x, speed_y, score ball_x += speed_x ball_y += speed_y # 左右边界反弹 if ball_x - ball_r <= 0 or ball_x + ball_r >= 600: speed_x = -speed_x # 顶部反弹 if ball_y - ball_r <= 0: speed_y = -speed_y # 挡板碰撞 if ball_y + ball_r >= paddle_y and paddle_x < ball_x < paddle_x + paddle_width: speed_y = -speed_y score += 5 canvas.itemconfig(score_text, text=f"分数:{score}") # 游戏结束 if ball_y + ball_r >= 500: canvas.create_text(300, 250, text="游戏结束!", fill="red", font=("微软雅黑", 30)) return # 更新小球位置 canvas.coords(ball, ball_x - ball_r, ball_y - ball_r, ball_x + ball_r, ball_y + ball_r) root.after(15, game_loop) # 启动游戏 game_loop() root.mainloop()

2025010094谢润泽
# 导入Python自带的画图工具(不用额外安装) import turtle import random # 1. 创建画布和画笔 screen = turtle.Screen() screen.title("漂亮的烟花") screen.bgcolor("black") # 黑色背景,烟花更好看 pen = turtle.Turtle() pen.speed(0) # 最快速度画画 pen.hideturtle() # 隐藏画笔,只看烟花 # 2. 定义画烟花的函数(新手也能看懂) def draw_firework(x, y): # 随机选烟花颜色 r = random.random() g = random.random() b = random.random() pen.color(r, g, b) # 把画笔移到点击的位置 pen.penup() pen.goto(x, y) pen.pendown() # 画烟花(一圈射线) for _ in range(36): pen.forward(100) pen.backward(100) pen.right(10) # 3. 绑定鼠标点击:点哪里,哪里放烟花 turtle.onscreenclick(draw_firework) # 4. 保持窗口不关闭 turtle.done()

2025010095徐雨轩
import numpy as np import matplotlib.pyplot as plt plt.rcParams["font.family"] = "SimHei" plt.rcParams["axes.unicode_minus"] = False fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(projection='3d') t = np.linspace(0, 8*np.pi, 1000) z = np.linspace(0, 12, 1000) x = 2 * np.cos(t) y = 2 * np.sin(t) ax.plot(x, y, z, color='blue', linewidth=2) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_title('三维螺旋上升线') plt.show()

2025010096刘加鑫
import tkinter as tk import random # 主窗口 root = tk.Tk() root.title("子弹打木块") root.geometry("600x400") cv = tk.Canvas(root, bg="white") cv.pack(fill=tk.BOTH, expand=True) # 全局变量 block = None bullet_list = [] block_x = 280 block_y = 50 block_speed = 3 # 创建移动木块 def create_block(): global block block = cv.create_rectangle(block_x, block_y, block_x+40, block_y+30, fill="red") # 木块自动左右移动 def move_block(): global block_x, block_speed block_x += block_speed if block_x <= 10 or block_x >= 550: block_speed *= -1 cv.coords(block, block_x, block_y, block_x+40, block_y+30) root.after(20, move_block) # 鼠标点击发射子弹 def fire_bullet(event): x = event.x y = event.y # 创建子弹小圆点 bullet = cv.create_oval(x-3, y-3, x+3, y+3, fill="blue") bullet_list.append([bullet, x, y]) # 子弹向上飞行 + 碰撞检测 def bullet_run(): del_list = [] block_pos = cv.coords(block) bx1, by1, bx2, by2 = block_pos for idx, (bul, x, y) in enumerate(bullet_list): new_y = y - 8 cv.coords(bul, x-3, new_y-3, x+3, new_y+3) bullet_list[idx][2] = new_y # 碰撞判断 if bx1 < x < bx2 and by1 < new_y < by2: cv.delete(bul) cv.delete(block) root.title("打中啦!") del_list.append(idx) # 飞出屏幕删除 if new_y < 0: del_list.append(idx) # 倒序删除避免下标错乱 for i in sorted(del_list, reverse=True): if i < len(bullet_list): bullet_list.pop(i) root.after(30, bullet_run) # 绑定鼠标左键发射 cv.bind("<Button-1>", fire_bullet) # 启动游戏 create_block() move_block() bullet_run() root.mainloop()

2025010097马浩
机器人指令
import re # 丰富的机器人指令列表 cmd_list = [ "向左走100米", "向右走60米", "向前走200米", "向后走80米", "原地左转90度", "原地右转45度", "停止运行", "加速前进", "向上走50米", "向下走30米" ] # 1. 筛选所有带行走距离的指令 walk_command = [cmd for cmd in cmd_list if "走" in cmd and "米" in cmd] print("筛选出行走类指令:") for c in walk_command: print(c) # 2. 正则提取每条指令的方向 + 距离 print("\n拆分方向和距离信息:") pattern = re.compile(r"(向左|向右|向前|向后|向上|向下)\s*走\s*(\d+)\s*米") for cmd in walk_command: res = pattern.search(cmd) if res: direct = res.group(1) distance = res.group(2) print(f"指令:{cmd} → 方向:{direct},距离:{distance}米")

2025010098韩晓媛
列表内容到文件
import csv#创建.csv格式文件 data_list=[ ["姓名", "年龄", "城市"], ["张三", 20, "北京"], ["李四", 22, "上海"], ["王五", 19, "广州"], ["赵六", 25, "浙江"] ] #创建文件,“W”是写入模式,“newline”是解决空行问题,“utf-8-sig”解决乱码问题 with open("Excel文件.csv", "w", newline="", encoding="utf-8-sig") as f: writer=csv.writer(f)#创建一个写入器对象 writer.writerows(data_list)#批量写入 print("导出成功!")

2025010099张嘉诚
停车场计费系统
from datetime import datetime import math def get_car_type(plate): if len(plate) < 2: return "未知车型" end_part = plate[2:] if len(end_part) == 5: return "油车" elif len(end_part) == 6: return "电车" return "未知车型" def count_hours(in_time_str, out_time_str): time_format = "%Y-%m-%d %H:%M" in_time = datetime.strptime(in_time_str.strip(), time_format) out_time = datetime.strptime(out_time_str.strip(), time_format) second_diff = (out_time - in_time).total_seconds() hour_num = second_diff / 3600 return math.ceil(hour_num) def count_fee(car_type, hour): if car_type == "油车": return hour * 2 elif car_type == "电车": return hour * 1 return 0 def main(): print("=======停车场计费系统=======") print("车型规则:车牌后5位=油车 后6位=电车") print("收费标准:油车2元/小时 电车1元/小时") print("计费规则:不足一小时按一小时计算") print("时间格式示例:2026-05-19 08:30\n") while True: car_plate = input("请输入车牌号(输入q退出):") if car_plate.upper() == "Q": print("系统已退出!") break car_type = get_car_type(car_plate) if car_type == "未知车型": print("❌ 车牌格式错误,无法识别车型!(去掉前两位后长度不是5或6位)\n") continue try: enter = input("请输入入场时间:") leave = input("请输入出场时间:") park_hour = count_hours(enter, leave) if park_hour <= 0: print("❌ 出场时间不能早于入场时间!\n") continue except ValueError as e: print(f"❌ 时间格式错误!必须填写:年-月-日 空格 时:分(冒号用英文半角)\n错误详情:{e}\n") continue money = count_fee(car_type, park_hour) print(f"车辆类型:{car_type}") print(f"计费时长:{park_hour} 小时") print(f"停车费用:{money} 元\n") if __name__ == "__main__": main()

2025010100霍延萌
判断数学式子是否正确
def check_brackets(expression):
# 用栈来保存左括号
stack = []
# 右括号 -> 对应左括号 的映射
bracket_map = {')': '(', ']': '[', '}': '{'}
for char in expression:
# 如果是左括号,入栈
if char in bracket_map.values():
stack.append(char)
# 如果是右括号
elif char in bracket_map:
# 栈为空,说明没有对应的左括号
if not stack:
return False
# 栈顶不是匹配的左括号,不匹配
if stack.pop() != bracket_map[char]:
return False
# 最后栈必须为空,才算全部匹配
return len(stack) == 0
# 主程序:输入式子并判断
if __name__ == "__main__":
print("=== 括号成对判断工具 ===")
math_expr = input("请输入数学式子:")
if check_brackets(math_expr):
print("✅ 括号完全成对,格式正确!")
else:
print("❌ 括号不成对或嵌套错误!")

2025010101袁泉
登陆网站界面
import tkinter as tk from tkinter import messagebox # 记录错误次数 error_count = 0 # 设定最大尝试次数 max_times = 3 def check_login(): global error_count # 获取输入的账号密码 username = entry_user.get().strip() pwd = entry_pwd.get().strip() # 正确账号密码(可自行修改) right_user = "admin" right_pwd = "123456" if username == right_user and pwd == right_pwd: messagebox.showinfo("成功", "登录成功!") root.destroy() # 登录成功关闭窗口 else: error_count += 1 remain = max_times - error_count if error_count >= max_times: messagebox.showerror("错误", "输错3次,程序自动退出!") root.destroy() else: messagebox.showerror("失败", f"账号或密码错误!还剩{remain}次机会") # 创建主窗口 root = tk.Tk() root.title("登录窗口") root.geometry("300x200") # 窗口大小 # 账号标签和输入框 label_user = tk.Label(root, text="账号:") label_user.pack(pady=5) entry_user = tk.Entry(root) entry_user.pack() # 密码标签和输入框 label_pwd = tk.Label(root, text="密码:") label_pwd.pack(pady=5) entry_pwd = tk.Entry(root, show="*") # 密码隐藏 entry_pwd.pack() # 登录按钮 btn_login = tk.Button(root, text="登录", command=check_login) btn_login.pack(pady=15) # 主循环 root.mainloop()

2025010102沈玉婷
把物理题中的中文单位换成英文单位
# 1. 输入一道物理题目 ti_mu = input("请输入物理题目:") # 2. 把中文单位替换成英文单位 ti_mu = ti_mu.replace("米", "m") ti_mu = ti_mu.replace("秒", "s") ti_mu = ti_mu.replace("千克", "kg") ti_mu = ti_mu.replace("千米", "km") ti_mu = ti_mu.replace("小时", "h") # 3. 输出转换后的题目 print("转换后题目:") print(ti_mu)

2025010103黄俊
图片循环播放
import tkinter as tk import os BOX_WIDTH = 500 BOX_HEIGHT = 500 INTERVAL = 200 pic_list = [] i = 1 while os.path.exists(f"img{i}.png"): pic_list.append(f"img{i}.png") i += 1 if not pic_list: print("❌ 没有找到任何图片!") exit() root = tk.Tk() root.title("完整图片循环播放") root.geometry(f"{BOX_WIDTH+40}x{BOX_HEIGHT+80}") frame = tk.Frame(root, width=BOX_WIDTH, height=BOX_HEIGHT, bg="white", relief="solid", bd=2) frame.pack(pady=20) label = tk.Label(frame, bg="white") label.place(relx=0.5, rely=0.5, anchor="center") current_index = 0 scale = 0.5 # 缩放比例,根据你的图片大小调整,0.5就是缩小一半 def update_image(): global current_index # 加载并缩放图片 img = tk.PhotoImage(file=pic_list[current_index]) # 按比例缩小 img = img.subsample(int(1/scale), int(1/scale)) label.config(image=img) label.image = img current_index = (current_index + 1) % len(pic_list) root.after(INTERVAL, update_image) update_image() root.mainloop()

2025010104许乐乐
设计导弹命中率,统计出和的命中率
# 手动输入设置每枚导弹命中率,计算整体命中概率 print("===== 导弹命中率计算系统 =====") n = int(input("请输入导弹数量:")) hit_list = [] # 逐个自定义输入命中率 for i in range(1, n + 1): p = float(input(f"请输入第{i}枚导弹命中率(输入0-1小数):")) hit_list.append(p) # 计算全部未命中概率 all_miss = 1.0 for rate in hit_list: all_miss *= (1 - rate) # 总命中率 total_hit = 1 - all_miss # 输出结果 print("\n----- 录入完成 -----") for idx, r in enumerate(hit_list, 1): print(f"第{idx}枚导弹命中率:{r*100:.1f}%") print(f"\n全部导弹齐射总命中率:{total_hit*100:.2f}%")

2025010106钟海洋
def send_qq_msg():
pyautogui.FAILSAFE = False
msg = input("请输入要发送的QQ消息:")
print("5秒内请点击QQ聊天输入框,确保光标闪烁!")
time.sleep(5)
pyautogui.typewrite(msg, interval=0.2)
time.sleep(0.5)
pyautogui.press('enter')
print("消息发送完成!")
if __name__ == "__main__":
send_qq_msg()

2025010107孙瑞妍
# 读取 text.txt 文件 with open("text.txt", "r", encoding="utf-8") as f: lines = f.readlines() while True: try: r = int(input("行:")) - 1 c = int(input("列:")) - 1 print(lines[r][c]) except: print("超出范围")

2025010097马浩
机器人指令
import re # 丰富的机器人指令列表 cmd_list = [ "向左走100米", "向右走60米", "向前走200米", "向后走80米", "原地左转90度", "原地右转45度", "停止运行", "加速前进", "向上走50米", "向下走30米" ] # 1. 筛选所有带行走距离的指令 walk_command = [cmd for cmd in cmd_list if "走" in cmd and "米" in cmd] print(walk_command) print("筛选出行走类指令:") for c in walk_command: print(c) # 2. 正则提取每条指令的方向 + 距离 print("\n拆分方向和距离信息:") pattern = re.compile(r"(向左|向右|向前|向后|向上|向下)\s*走\s*(\d+)\s*米") for cmd in walk_command: res = pattern.search(cmd) if res: direct = res.group(1) distance = res.group(2) print(f"指令:{cmd} → 方向:{direct},距离:{distance}米")

2025010109 黄帅豪
联网发送
客户端: import socket import tkinter as tk import tkinter.messagebox from threading import Thread # 创建tcp客户端 class TcpClientSocket: def __init__(self): self.tcp_client_socket = None self.root = tk.Tk() self.root.title('tcp客户端') self.root.geometry('500x350') # 连接 self.con_btn = tk.Button(self.root, text="连接服务端", width=10, command=self.connect) self.con_btn.place(x=100, y=20) # 断开连接 self.discon_btn = tk.Button(self.root, text="断开连接", width=10, command=self.disconnect) self.discon_btn.place(x=300, y=20) # 文本输入框 self.send_entry = tk.Entry(self.root, width=50) self.send_entry.place(x=50, y=80) # 发送消息按钮 self.send_btn = tk.Button(self.root, text="发送消息", command=self.send) self.send_btn.place(x=420, y=75) # 消息框 self.msg_test = tk.Text(self.root, width=70, height=16) self.msg_test.place(x=2, y=125) self.root.mainloop() # 连接服务端 def connect(self): try: if self.tcp_client_socket: tk.messagebox.showinfo('提示', '已是连接状态') # 每次连接服务端就将上一次的记录清除 self.msg_test.delete(1.0, tk.END) self.send_entry.delete(0, tk.END) # 创建客户端socket self.tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接,端口可以改变 self.tcp_client_socket.connect(('127.0.0.1', 8888)) self.msg_test.insert(tk.END, "连接到服务端, 请输入信息...\n") except Exception as e: self.msg_test.insert(tk.END, f"连接失败的原因是: {e}") # 发送消息 def send(self): # 从输入框获取数据 input_data = self.send_entry.get() self.tcp_client_socket.send(input_data.encode(encoding='utf-8')) self.msg_test.insert(tk.END, f"客户端:{str(input_data)}\n") # 使用线程,防止未响应 receive_thread = Thread(target=self.receive, daemon=True) receive_thread.start() def receive(self): if self.tcp_client_socket: rec_msg = self.tcp_client_socket.recv(1024).decode(encoding='utf-8') self.msg_test.insert(tk.END, f"服务端:{str(rec_msg)}\n") # 断开连接 def disconnect(self): if self.tcp_client_socket: self.send_entry.delete(0, tk.END) self.msg_test.insert(tk.END, "断开连接") self.tcp_client_socket.send('#'.encode(encoding='utf-8')) # 发送'#‘断开连接 self.tcp_client_socket.close() # 关闭客户端 else: tk.messagebox.showinfo('提示', '未连接到服务端') if __name__ == '__main__': TcpClientSocket() 服务端: import socket import tkinter as tk from threading import Thread import tkinter.messagebox class TcpServerSocket: def __init__(self): self.conn_socket = None self.tcp_server_socket = None self.root = tk.Tk() self.root.title('tcp服务端') self.root.geometry('500x350') # 连接 self.con_btn = tk.Button(self.root, text="启动服务端", width=10, command=self.start_server) self.con_btn.place(x=100, y=20) # 接收消息 self.status_btn = tk.Button(self.root, text="接收连接", width=10, command=self.status) self.status_btn.place(x=200, y=20) # 接收消息 self.rev_btn = tk.Button(self.root, text="接收消息", command=self.receive) self.rev_btn.place(x=300, y=20) # 文本输入框 self.send_entry = tk.Entry(self.root, width=50) self.send_entry.place(x=50, y=80) # 发送消息按钮 self.send_btn = tk.Button(self.root, text="发送消息", command=self.send) self.send_btn.place(x=420, y=75) # 消息框 self.msg_test = tk.Text(self.root, width=70, height=16) self.msg_test.place(x=2, y=125) self.root.mainloop() # 启动tcp服务端 def start_server(self): try: # 每次连接服务端就将上一次的记录清除 self.send_entry.delete(0, tk.END) self.msg_test.delete(1.0, tk.END) # 创建服务端socket self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_server_socket.bind(('', 8888)) # 绑定 self.tcp_server_socket.listen(5) # 监听的最大连接数 self.msg_test.insert(tk.END, f"服务端启动成功!\n") except Exception as e: self.msg_test.insert(tk.END, f"启动失败的原因是: {e}") def status(self): if self.conn_socket is None: self.conn_socket, ip_port = self.tcp_server_socket.accept() elif self.conn_socket: self.msg_test.insert(tk.END, "客户端已连接\n") else: tk.messagebox.showinfo('提示', "客户端未连接") def send(self): try: input_data = self.send_entry.get() self.conn_socket.send(input_data.encode(encoding='utf-8')) self.msg_test.insert(tk.END, f"服务端:{str(input_data)}\n") except Exception as e: self.msg_test.insert(tk.END, f"发送失败的原因: {e}") def receive(self): rec_msg = self.conn_socket.recv(1024).decode(encoding='utf-8') print(rec_msg) # 获取到#断开连接 if rec_msg == '#': self.conn_socket.close() self.tcp_server_socket.close() self.msg_test.insert(tk.END, f"客户端断开连接\n") return self.msg_test.insert(tk.END, f"客户端:{str(rec_msg)}\n") if __name__ == '__main__': TcpServerSocket()

2025010112 王怡萱
def is_leap(year): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return True return False def get_month_days(year, month): month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month == 2 and is_leap(year): return 29 return month_days[month - 1] def date_minus_day(y, m, d, minus_days): now_y = y now_m = m now_d = d for _ in range(minus_days): now_d -= 1 if now_d < 1: now_m -= 1 if now_m < 1: now_y -= 1 now_m = 12 now_d = get_month_days(now_y, now_m) return now_y, now_m, now_d y, m, d = date_minus_day(2026, 5, 6, 10) print(f"2026-05-06 减去10天 = {y}-{m:02d}-{d:02d}")

2025010108叱干育


2025010113 石蕊鑫
截取对话并统计几人对话、分别说了几句话
if __name__ == "__main__": chat_data = """ A:大家晚上好 B:晚上好呀 A:明天有没有空 A:我有空 B:我也可以 A:那明天上午集合 C:没问题 """ def stat_chat(text): lines = text.strip().splitlines() res = {} for line in lines: line = line.strip() if not line or ":" not in line: continue name = line.split(":")[0] res[name] = res.get(name, 0) + 1 return res result = stat_chat(chat_data) total_people = len(result) total_msg = sum(result.values()) print("===== 群聊天统计结果 =====") print(f"发言总人数:{total_people} 人") print(f"总发言条数:{total_msg} 条") print("-" * 20) for name, count in result.items(): print(f"{name} 说了 {count} 句话")

2025010114 殷佳锐
英语文章句子第一个字母大写
# 获取用户输入整篇英文 text = input("请输入英文文章:") # 按句号分割句子 lst = text.split(".") res = "" # 循环给每个句子首字母大写 for s in lst: if s.strip() != "": res += s.strip().capitalize() + ". " # 输出最终结果 print("\n转换后(每句首字母大写):") print(res)

2025010115 康静茹
建立一个评阅表excel,输出评阅教师人数
# 自动安装并导入pandas import subprocess import sys def install_pandas(): subprocess.check_call([ sys.executable, "-m", "pip", "install", "pandas", "openpyxl", "--user", "-i", "https://pypi.tuna.tsinghua.edu.cn/simple" ]) try: import pandas as pd except ImportError: print("正在自动安装库...") install_pandas() import pandas as pd # 读取Excel文件(改成你自己的文件路径) df = pd.read_excel(r"D:\评阅表.xlsx", engine="openpyxl") # ---------------------- 关键修改部分 ---------------------- # 假设你的表格里,评阅教师的列名是“评阅教师”,如果不是,改成你实际的列名 teacher_col = "评阅教师" # 这里要和Excel里的列名完全一致 # 去重,获取所有不重复的教师名称 unique_teachers = df[teacher_col].dropna().unique() # 统计人数 teacher_count = len(unique_teachers) # 输出结果 print("===== 评阅教师统计 =====") print(f"评阅教师总人数:{teacher_count} 人") print("评阅教师名单:") for idx, name in enumerate(unique_teachers, 1): print(f"{idx}. {name}")

2025010117 李欣栎
视频截图,截图保存到文件里
import cv2 import os def save_video_screenshots(video_path, save_dir="video_screenshots", interval=10): # 创建保存截图的文件夹 if not os.path.exists(save_dir): os.makedirs(save_dir) # 打开视频文件 cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("无法打开视频文件,请检查路径!") return count = 0 # 截图计数器 while True: ret, frame = cap.read() if not ret: break # 视频读取结束 # 每隔 interval 帧保存一张截图 if count % interval == 0: screenshot_path = os.path.join(save_dir, f"screenshot_{count}.jpg") cv2.imwrite(screenshot_path, frame) print(f"已保存:{screenshot_path}") count += 1 cap.release() print("视频截图完成!") # ---------------------- 使用方法 ---------------------- # 替换成你的视频文件路径 video_file = "414d955f22100c9a287b66d49e20f7d5.MP4" save_video_screenshots(video_file, interval=30)


2025010118 陈影
判断各朝代诗人
#定义列表(作者,朝代) poets= [("李白", "唐"),("杜甫", "唐"),("王维", "唐"),("白居易", "唐"), ("苏轼", "宋"),("辛弃疾", "宋"),("李清照", "宋"),("陆游", "宋"), ("陶渊明", "晋"),("曹操", "三国"), ("曹植", "三国"),("王之涣", "唐"),("王安石", "宋")] #创建空字典 count = {} #遍历列表 for name, dynasty in poets: if dynasty in count: count[dynasty] += 1 else: count[dynasty] = 1 # 输出结果 print("各朝代诗人人数:") for dynasty, num in count.items(): print(f"{dynasty}代:{num}人")
2025010119 淡郑雪
判断括号
def is_valid_brackets(s): stack = [] # 建立右括号到左括号的映射 mapping = {')': '(', ']': '[', '}': '{'} for char in s: # 如果是左括号,直接入栈 if char in mapping.values(): stack.append(char) # 如果是右括号 elif char in mapping: # 栈为空 或 栈顶元素不匹配 if not stack or stack.pop() != mapping[char]: return False # 其他字符(比如字母、数字)直接忽略 else: continue # 遍历完后栈必须为空,才算全部匹配 return len(stack) == 0 # 测试 if __name__ == "__main__": test_cases = [ "()", "()[]{}", "(]", "([)]", "{[]}", "a(b)c[d]e{f}g", "((()))", "(()" ] for case in test_cases: print(f"式子 '{case}' 是否正确:{is_valid_brackets(case)}")

2025010121郑舒萍
把文件名中含A的复制到另一个新的文件中
import os import shutil # 新建目标文件夹 if not os.path.exists("a_files"): os.mkdir("a_files") # 遍历当前目录的所有内容 for filename in os.listdir("."): # 只处理文件,跳过文件夹(比如.idea、venv这些) if os.path.isfile(filename): # 文件名包含a的文件(不区分大小写) if "a" in filename.lower(): shutil.copy(filename, os.path.join("a_files", filename)) print("✅ 复制完成!所有含a的文件已放到 a_files 文件夹")

2025010120刘司拓
小球碰撞游戏


2025010122田昌盛
打字游戏气球爆炸
import pygame import random # 初始化 pygame.init() W, H = 800, 600 screen = pygame.display.set_mode((W, H)) pygame.display.set_caption("气球打字游戏") clock = pygame.time.Clock() # 颜色 WHITE = (255, 255, 255) BG_COLOR = (135, 206, 235) BALL_COLORS = [(255, 68, 68), (68, 170, 255), (68, 221, 68), (255, 170, 0), (170, 68, 255)] letters = "abcdefghijklmnopqrstuvwxyz" # 字体 font = pygame.font.SysFont(None, 40) # 气球类 class Balloon: def __init__(self): self.char = random.choice(letters) self.color = random.choice(BALL_COLORS) self.x = random.randint(30, W - 30) self.y = -50 self.speed = random.uniform(2, 4) self.radius = 25 self.boom = False self.boom_frame = 0 def update(self): if not self.boom: self.y += self.speed else: self.boom_frame += 1 def draw(self, surf): if not self.boom: pygame.draw.circle(surf, self.color, (int(self.x), int(self.y)), self.radius) text = font.render(self.char.upper(), True, WHITE) surf.blit(text, (self.x - 12, self.y - 15)) else: # 爆炸效果 scale = 1 + self.boom_frame * 0.2 r = int(self.radius * scale) pygame.draw.circle(surf, self.color, (int(self.x), int(self.y)), r, 3) def is_out(self): return self.y > H + 20 or (self.boom and self.boom_frame > 10) # 游戏主循环 balloons = [] spawn_timer = 0 FPS = 60 running = True while running: dt = clock.tick(FPS) screen.fill(BG_COLOR) # 事件监听 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: key = pygame.key.name(event.key) # 匹配气球 for b in balloons: if b.char == key and not b.boom: b.boom = True break # 生成气球 spawn_timer += dt if spawn_timer > 1200: balloons.append(Balloon()) spawn_timer = 0 # 更新&绘制气球 for b in balloons: b.update() b.draw(screen) # 移除消失/爆炸的气球 balloons = [b for b in balloons if not b.is_out()] pygame.display.flip() pygame.quit()

2025010124 胡鑫
import turtle # 新建绘图窗口 screen = turtle.Screen() screen.title("路灯渐变延伸效果") screen.bgcolor("lightblue") pen = turtle.Turtle() pen.hideturtle() pen.speed(0) # 循环绘制5盏逐渐缩小、向后延伸的路灯 for n in range(5): size = 1 - n * 0.18 # 依次缩小 pos_x = -200 + n * 90 # 依次右移延伸 pos_y = -80 + n * 25 # 近低远高透视 pen.penup() pen.goto(pos_x, pos_y) pen.pendown() # 画灯杆 pen.pensize(5 * size) pen.pencolor("#333333") pen.setheading(90) pen.forward(70 * size) # 画灯臂 pen.setheading(0) pen.forward(22 * size) # 画路灯灯头 pen.pencolor("#ffcc00") pen.dot(16 * size) # 窗口保持常驻 turtle.done()

2025010125 刘芮孜
筛选天气情况
print("安康近15天天气预报") print("--------------------------") # 安康近15天天气数据:(日期, 天气, 温度, 风向) weather_data = [ ("05月13日", "晴", 28, "微风"), ("05月14日", "多云", 26, "南风2级"), ("05月15日", "小雨", 22, "东风3级"), ("05月16日", "阴", 24, "微风"), ("05月17日", "晴", 29, "西风2级"), ("05月18日", "多云", 27, "微风"), ("05月19日", "雷阵雨", 23, "北风3级"), ("05月20日", "小雨", 21, "东风2级"), ("05月21日", "阴", 23, "微风"), ("05月22日", "晴", 28, "南风2级"), ("05月23日", "多云", 26, "微风"), ("05月24日", "晴", 30, "西风2级"), ("05月25日", "小雨", 22, "东风3级"), ("05月26日", "阴", 24, "微风"), ("05月27日", "晴", 29, "南风2级") ] # 只提取日期和天气,去掉“天气预报”字样 for t, w, _, _ in weather_data: print(f"{t}: {w}")

2025010127 刘杨龙
import turtle import random # 设置画布 t = turtle.Turtle() t.speed(0) turtle.bgcolor("black") colors = ["red", "yellow", "blue", "pink", "orange", "white"] # 绘制单朵烟花 def firework(x, y): t.penup() t.goto(x, y) t.pendown() t.color(random.choice(colors)) # 放射线条模拟烟花 for _ in range(36): t.forward(80) t.backward(80) t.right(10) # 连续生成随机位置烟花 for _ in range(8): x = random.randint(-300, 300) y = random.randint(-200, 200) firework(x, y) t.hideturtle() turtle.done()

2025010128 贾姝慧
加载图
import tkinter # 创建窗口 root = tkinter.Tk() root.title("加载图") root.geometry("300x180") # 显示文字 label = tkinter.Label(root, text="正在加载", font=("黑体", 40)) label.pack(expand=True) # 转圈符号 chars = ["|", "/", "-", "\\"] index = 0 def load(): global index # 更新文字 label.config(text=f"正在加载 {chars[index]}") index += 1 # 循环 if index >= 4: index = 0 # 定时调用 root.after(150, load) # 启动 load() root.mainloop()

2025010130 任鸿杰
车票筛选窗口
import tkinter as tk from tkinter import ttk # 模拟车次数据 train_data = [ {"train_no": "G101", "start": "北京", "end": "上海", "start_time": "08:00", "arrive_time": "13:20"}, {"train_no": "D202", "start": "南京", "end": "杭州", "start_time": "09:10", "arrive_time": "11:05"}, {"train_no": "G103", "start": "北京", "end": "广州", "start_time": "10:30", "arrive_time": "18:40"}, {"train_no": "K501", "start": "西安", "end": "成都", "start_time": "14:00", "arrive_time": "次日06:20"}, {"train_no": "G105", "start": "上海", "end": "北京", "start_time": "15:20", "arrive_time": "20:10"}, {"train_no": "D305", "start": "南京", "end": "苏州", "start_time": "07:30", "arrive_time": "08:45"} ] def filter_train(): """筛选车次核心逻辑""" start_city = entry_start.get().strip() end_city = entry_end.get().strip() s_time = entry_stime.get().strip() e_time = entry_etime.get().strip() # 清空表格 tree.delete(*tree.get_children()) # 遍历筛选 for train in train_data: # 出发地筛选 if start_city and train["start"] != start_city: continue # 目的地筛选 if end_city and train["end"] != end_city: continue # 出发时间段筛选 train_st = train["start_time"] if s_time and e_time: if not (s_time <= train_st <= e_time): continue # 插入结果 tree.insert("", "end", values=( train["train_no"], train["start"], train["end"], train["start_time"], train["arrive_time"] )) # 创建主窗口 root = tk.Tk() root.title("车次筛选系统") root.geometry("750x450") # 布局组件 tk.Label(root, text="出发地:", font=("微软雅黑", 10)).place(x=30, y=20) entry_start = tk.Entry(root, width=15, font=("微软雅黑", 10)) entry_start.place(x=90, y=20) tk.Label(root, text="目的地:", font=("微软雅黑", 10)).place(x=230, y=20) entry_end = tk.Entry(root, width=15, font=("微软雅黑", 10)) entry_end.place(x=290, y=20) tk.Label(root, text="起始时段:", font=("微软雅黑", 10)).place(x=30, y=60) entry_stime = tk.Entry(root, width=12, font=("微软雅黑", 10)) entry_stime.place(x=90, y=60) tk.Label(root, text="结束时段:", font=("微软雅黑", 10)).place(x=200, y=60) entry_etime = tk.Entry(root, width=12, font=("微软雅黑", 10)) entry_etime.place(x=260, y=60) # 筛选按钮 btn_search = tk.Button(root, text="开始筛选", command=filter_train, bg="#1E90FF", fg="white", font=("微软雅黑", 10)) btn_search.place(x=400, y=40) # 结果表格 cols = ("车次", "出发站", "到达站", "发车时间", "到达时间") tree = ttk.Treeview(root, columns=cols, show="headings", height=15) for col in cols: tree.heading(col, text=col) tree.column(col, width=130, anchor="center") tree.place(x=20, y=100) root.mainloop()

2025010131 董玥卓
红楼梦切词
# 红楼梦简易分词(纯内置库,无第三方依赖) def simple_cut(text): # 定义红楼高频断词符号、标点 punct = ",。、;:?!‘’“”()《》【】……——\n\r\t " words = [] temp = "" # 逐字符遍历分词 for char in text: if char in punct: if temp: words.append(temp) temp = "" else: temp += char if temp: words.append(temp) return words # 1. 模拟红楼梦文本(可替换为完整小说文本) honglou_text = """ 满纸荒唐言,一把辛酸泪。 都云作者痴,谁解其中味。 开辟鸿蒙,谁为情种?都只为风月情浓。 """ # 2. 执行分词 result = simple_cut(honglou_text) # 3. 输出结果 print("分词结果:") print(result)

2025010132 李佳雨
论文指导表
# 论文指导表分配生成代码 student_total = 40 # 学生总数 reviewer_total = 10 # 评阅老师总数 stu_per_reviewer = 4 # 每位评阅老师负责学生数 print("学生编号\t指导老师\t评阅老师") print("-" * 30) for stu_id in range(1, student_total + 1): # 计算对应评阅老师编号 reviewer_no = (stu_id - 1) // stu_per_reviewer + 1 # 编号补零格式化 stu_code = f"S{stu_id:02d}" tutor_code = f"T{stu_id:02d}" reviewer_code = f"R{reviewer_no:02d}" print(f"{stu_code}\t\t{tutor_code}\t\t{reviewer_code}")


浙公网安备 33010602011771号