大家好!欢迎来到奥饼饼智慧谷 🎲。今天我们来做一个实用又有趣的工具——随机抽取器!可以用来抽奖、随机分组、选择午餐等等,用途多多!
🎯 功能介绍
这个随机抽取器会有这些功能:
💡 使用小贴士
用它来决定今天吃什么,再也不用纠结了!
🎲 开始写代码
以下是完整的随机抽取器代码:
import random import json import os from datetime import datetime DATA_DIR = "lottery_data" HISTORY_FILE = os.path.join(DATA_DIR, "history.json") def ensure_dir(): """确保数据目录存在""" if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR) def save_list(name, items): """保存抽取列表""" ensure_dir() filename = os.path.join(DATA_DIR, f"{name}.json") with open(filename, 'w', encoding='utf-8') as f: json.dump(items, f, ensure_ascii=False, indent=2) print(f"✅ 列表 '{name}' 已保存!") def load_list(name): """加载抽取列表""" filename = os.path.join(DATA_DIR, f"{name}.json") if not os.path.exists(filename): print(f"❌ 列表 '{name}' 不存在!") return None with open(filename, 'r', encoding='utf-8') as f: return json.load(f) def list_all_lists(): """列出所有可用的抽取列表""" ensure_dir() files = [f[:-5] for f in os.listdir(DATA_DIR) if f.endswith('.json') and f != 'history.json'] if not files: print("\n📭 还没有抽取列表") return [] print("\n" + "="*50) print(" 📋 可用的抽取列表") print("="*50) for i, name in enumerate(files, 1): items = load_list(name) count = len(items) if items else 0 print(f"{i}. {name} ({count} 个选项)") print("="*50) return files def add_items(): """创建新的抽取列表""" print("\n" + "="*40) print(" ➕ 创建抽取列表") print("="*40) name = input("\n请输入列表名称: ").strip() if not name: print("❌ 名称不能为空!") return print("\n请输入选项(每行一个,输入空行结束):") items = [] while True: item = input().strip() if not item: break # 检查是否有概率设置(格式: 选项|权重) if '|' in item: parts = item.split('|', 1) item_name = parts[0].strip() try: weight = int(parts[1].strip()) except ValueError: weight = 1 items.append({"name": item_name, "weight": weight}) else: items.append({"name": item, "weight": 1}) if not items: print("❌ 没有添加任何选项!") return save_list(name, items) print(f"\n已添加 {len(items)} 个选项:") for item in items: if item['weight'] != 1: print(f" - {item['name']} (权重: {item['weight']})") else: print(f" - {item['name']}") def draw_items(): """进行随机抽取""" lists = list_all_lists() if not lists: return while True: try: choice = input("\n请选择列表编号: ").strip() index = int(choice) - 1 if 0 <= index < len(lists): list_name = lists[index] break print("❌ 请输入有效的编号!") except ValueError: print("❌ 请输入有效的数字!") items = load_list(list_name) if not items: return print(f"\n🎯 列表 '{list_name}' 有 {len(items)} 个选项:") for i, item in enumerate(items, 1): weight_info = f" (权重: {item['weight']})" if item['weight'] != 1 else "" print(f"{i}. {item['name']}{weight_info}") while True: try: count = input("\n请输入要抽取的数量 (1-10): ").strip() num = int(count) if 1 <= num <= 10: break print("❌ 请输入 1-10 的数字!") except ValueError: print("❌ 请输入有效的数字!") # 准备带权重的抽取 weighted_items = [] for item in items: weighted_items.extend([item] * item['weight']) # 进行抽取 print("\n" + "="*50) print(" 🎲 抽取中...") print("="*50) results = [] for i in range(num): selected = random.choice(weighted_items) results.append(selected['name']) print(f"{i + 1}. {selected['name']}") print("="*50) # 保存历史记录 save_history(list_name, results) print(f"\n🎉 抽取完成!共抽取了 {num} 个选项!") def save_history(list_name, results): """保存抽取历史""" ensure_dir() history = [] if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, 'r', encoding='utf-8') as f: history = json.load(f) record = { "list": list_name, "results": results, "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S") } history.insert(0, record) history = history[:50] # 只保留最近50条记录 with open(HISTORY_FILE, 'w', encoding='utf-8') as f: json.dump(history, f, ensure_ascii=False, indent=2) def view_history(): """查看抽取历史""" if not os.path.exists(HISTORY_FILE): print("\n📭 还没有抽取记录") return with open(HISTORY_FILE, 'r', encoding='utf-8') as f: history = json.load(f) if not history: print("\n📭 还没有抽取记录") return print("\n" + "="*70) print(" 📜 抽取历史记录") print("="*70) print(f"{'序号':<8} {'时间':<20} {'列表':<15} {'结果'}") print("-"*70) for i, record in enumerate(history[:20], 1): results_str = ", ".join(record['results']) print(f"{i:<8} {record['time']:<20} {record['list']:<15} {results_str}") print("="*70) if len(history) > 20: print(f"... 还有 {len(history) - 20} 条记录") def main(): print("="*40) print(" 🎲 欢迎来到随机抽取器! 🎲") print("="*40) while True: print("\n" + "-"*40) print("1. 创建抽取列表") print("2. 查看所有列表") print("3. 开始抽取") print("4. 查看抽取历史") print("5. 退出") print("-"*40) choice = input("\n请选择 (1-5): ").strip() if choice == "1": add_items() elif choice == "2": list_all_lists() elif choice == "3": draw_items() elif choice == "4": view_history() elif choice == "5": print("\n👋 再见!祝你好运!") break else: print("❌ 请选择 1-5!") if __name__ == "__main__": main()
当你面临选择困难时,让随机来帮你做决定!有时候,不确定的选择反而会带来惊喜!
🚀 运行试试吧!
保存为 `lottery.py` 然后运行:
python lottery.py
创建几个抽取列表,比如"午餐选择"、"学习计划",然后开始随机抽取吧!
✨ 进阶玩法
想让这个抽取器更强大?试试这些改进:
🎁 创意用法
可以用来决定每天的学习任务,或者随机选择一本要读的书!
📚 知识要点
通过这个项目,我们学到了:
今天的随机抽取器就到这里了!快去创建几个列表,让随机给你带来惊喜吧!🎲
👋 感谢阅读 | 奥饼饼智慧谷
每天一个有趣的编程小项目,让学习变成乐趣!
💡 点赞 + 在看 + 分享,让更多人一起享受编程的快乐!