编写代码完成将生成的算式及习题长期保存下来,采用CSV、XML、JSON三种形式进行存储并读取。提交相关代码及运行截图。
import random import csv import json import xml.etree.ElementTree as ET from xml.dom import minidom # 生成随机算式数据 def generate_exercises(count=10): exercises = [] operators = ['+', '-', '*', '/'] for _ in range(count): num1 = random.randint(1, 10) num2 = random.randint(1, 10) operator = random.choice(operators) # 确保不会出现除以零的情况 if operator == '/' and num2 == 0: num2 = 1 expression = f"{num1} {operator} {num2}" result = eval(expression) # 使用eval计算表达式的结果 exercises.append({"expression": expression, "result": result}) return exercises # CSV 存储与读取 def save_to_csv(data, filename): with open(filename, 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Expression', 'Result']) for item in data: writer.writerow([item['expression'], item['result']]) def load_from_csv(filename): with open(filename, 'r') as file: reader = csv.DictReader(file) return [row for row in reader] # JSON 存储与读取 def save_to_json(data, filename): with open(filename, 'w') as file: json.dump(data, file, indent=4) def load_from_json(filename): with open(filename, 'r') as file: return json.load(file) # XML 存储与读取 def save_to_xml(data, filename): root = ET.Element("Exercises") for item in data: exercise = ET.SubElement(root, "Exercise") ET.SubElement(exercise, "Expression").text = str(item['expression']) ET.SubElement(exercise, "Result").text = str(item['result']) tree = ET.ElementTree(root) xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ") with open(filename, 'w') as f: f.write(xmlstr) def load_from_xml(filename): tree = ET.parse(filename) root = tree.getroot() exercises = [] for exercise in root.findall('Exercise'): expression = exercise.find('Expression').text result = float(exercise.find('Result').text) # 假设结果都是数字 exercises.append({"expression": expression, "result": result}) return exercises # 主程序 def main(): print("请选择操作:") print("1. 生成新的算式并保存") print("2. 从文件加载算式") choice = input("请输入选项 (1 或 2): ") if choice == '1': count = int(input("请输入要生成的算式数量: ")) exercises = generate_exercises(count) format_choice = input("请选择保存格式 (csv, json, xml): ").strip().lower() if format_choice == 'csv': save_to_csv(exercises, 'exercises.csv') print("算式已保存到 exercises.csv 文件中.") elif format_choice == 'json': save_to_json(exercises, 'exercises.json') print("算式已保存到 exercises.json 文件中.") elif format_choice == 'xml': save_to_xml(exercises, 'exercises.xml') print("算式已保存到 exercises.xml 文件中.") else: print("未知的文件格式,请输入 csv, json 或 xml.") elif choice == '2': format_choice = input("请选择加载的文件格式 (csv, json, xml): ").strip().lower() if format_choice == 'csv': loaded_data = load_from_csv('exercises.csv') elif format_choice == 'json': loaded_data = load_from_json('exercises.json') elif format_choice == 'xml': loaded_data = load_from_xml('exercises.xml') else: print("未知的文件格式,请输入 csv, json 或 xml.") return print(f"从 {format_choice} 文件加载的数据:") print(loaded_data) else: print("无效的选择,请输入 1 或 2.") if __name__ == "__main__": main()
标签:XML,xml,算式,json,choice,JSON,filename,exercises,csv From: https://www.cnblogs.com/youxiandechilun/p/18460700