我想在某个主题标签(字符串)之后读取和写入成绩(数字)。所以我有一切,但我无法弄清楚如何找到标签并在不替换后面的数字后写。
因此,例如,有效输入将是:
MAT54324524342211
到目前为止我尝试过的事情:
save = open("grades.txt", "w")
def add(x, y):
z = x / y * 100
return z
def calc_grade(perc):
if perc < 50:
return "1"
if perc < 60:
return "2"
if perc < 75:
return "3"
if perc < 90:
return "4"
if perc >= 90:
return "5"
def calc_command():
num1 = input("Input your points: ")
num2 = input("Input maximum points: ")
num3 = add(float(num1), float(num2))
grade = calc_grade(num3)
print("This is your result:", str(num3) + "%")
print("Your grade:", grade)
save.write(grade)
while True:
command = input("Input your command: ")
if command == "CALC":
calc_command()
if command == "EXIT":
break
有什么想法吗? 嘿抱歉这是我的代码的旧版本。新版本是在打印后我的成绩是save.write(等级)。程序尚未完成。最后的想法是,我将在我的txt文件中获得一堆主题标签,然后用户将选择哪个主题是成绩。
答案 0 :(得分:0)
请尽量不重新实现标准库中已有的内容。
使用json对脚本进行一些实现将是:
import os
import json
def read_grades(filename):
if os.path.exists(filename):
with open(filename, 'r') as f:
try:
return json.loads(f.read())
except ValueError as ex:
print('could not read', ex)
return {}
def write_grades(filename, grades):
with open(filename, 'w') as f:
try:
f.write(
json.dumps(grades, indent=2, sort_keys=True)
)
except TypeError as ex:
print('could not write', ex)
def question(text, cast=str):
try:
inp = input(text)
return cast(inp)
except Exception as ex:
print('input error', ex)
return question(text, cast=cast)
def calculator(grades):
def add(x, y):
assert y != 0, 'please don\'t do that'
z = x / y
return z * 100
def perc(res):
for n, p in enumerate([50, 60, 75, 90], start=1):
if res < p:
return n
return 5
subject = question('enter subject: ').strip()
points = question('your points: ', cast=float)
max_points = question('maximum points: ', cast=float)
result = add(points, max_points)
grade = perc(result)
print('> {subject} result: {result:.2f}% grade: {grade}'.format(
subject=subject.capitalize(),
result=result, grade=grade
))
grades.setdefault(subject.lower(), list())
grades[subject.lower()].append(grade)
return grades
def show(grades):
print('>> grades')
for subject in sorted(grades.keys()):
print('> {subject}: {grades}'.format(
subject=subject.capitalize(),
grades='; '.join(str(g) for g in grades[subject])
))
def main():
filename = 'grades.json'
grades = read_grades(filename)
while True:
grades = calculator(grades)
show(grades)
if not question('continue? (hit enter to quit) '):
break
write_grades(filename, grades)
if __name__ == '__main__':
main()
grades.json
现在包含一个dictionary
,主题为主键,所有等级中list
为值:
{
"art": [
3
],
"math": [
4,
5
]
}