随机生成算式,采用csv、json、xml方式存储并读取

import random

import csv

import json

import xml.etree.ElementTree as ET

 

 

def generate_expression():

operators = ['+', '-', '*', '/']

num1 = random.randint(1, 10)

num2 = random.randint(1, 10)

operator = random.choice(operators)

expression = f"{num1} {operator} {num2}"

return expression

 

def save_expressions_csv(expressions):

with open('expressions.csv', 'a', newline='') as file:

writer = csv.writer(file)

for expr in expressions:

writer.writerow([expr])

 

def save_expressions_json(expressions):

with open('expressions.json', 'a') as file:

json.dump(expressions, file)

file.write('\n')

 

def save_expressions_xml(expressions):

root = ET.Element("Expressions")

for expr in expressions:

ET.SubElement(root, "Expression").text = expr

tree = ET.ElementTree(root)

with open("expressions.xml", "wb") as file:

tree.write(file)

 

def read_expressions_csv():

try:

with open('expressions.csv', 'r') as file:

reader = csv.reader(file)

return [row[0] for row in reader]

except FileNotFoundError:

return []

 

def read_expressions_json():

expressions = []

try:

with open('expressions.json', 'r') as file:

for line in file:

expressions.extend(json.loads(line))

except FileNotFoundError:

return []

return expressions

 

def read_expressions_xml():

try:

tree = ET.parse('expressions.xml')

root = tree.getroot()

return [expr.text for expr in root.findall('Expression')]

except FileNotFoundError:

return []

 

def main():

while True:

print("选择操作:")

print("1. 生成算式并存储")

print("2. 读取算式")

choice = input("请输入你的选择 (1或2): ")

 

if choice == '1':

count = int(input("请输入要生成的新算式的数量: "))

storage_format = input("选择存储方式 (CSV, JSON, XML): ").strip().lower()

expressions = [generate_expression() for _ in range(count)]

if storage_format == 'csv':

save_expressions_csv(expressions)

elif storage_format == 'json':

save_expressions_json(expressions)

elif storage_format == 'xml':

save_expressions_xml(expressions)

else:

print("无效的存储方式.")

print(f"已生成并存储 {count} 个算式.")

 

elif choice == '2':

read_format = input("选择读取方式 (CSV, JSON, XML): ").strip().lower()

if read_format == 'csv':

expressions = read_expressions_csv()

elif read_format == 'json':

expressions = read_expressions_json()

elif read_format == 'xml':

expressions = read_expressions_xml()

else:

print("无效的读取方式.")

continue

 

if expressions:

print("已存储的算式:")

for expr in expressions:

print(expr)

else:

print("没有找到任何存储的算式.")

 

else:

print("无效的选择,请重新输入.")

 

if __name__ == "__main__":

main()

 

posted @ 2024-10-14 21:13  涨涨涨张  阅读(5)  评论(0编辑  收藏  举报