You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决E-learning模块中仅显示当前测验得分的问题?

问题描述

我开发了一个带测验功能的E-learning模块,但用户完成测验后,仅显示当前模块的得分,其余模块得分会被重置为0:

  • 完成模块1测验时显示:

    Fundamentals of Networking: Score - 10
    Network Tools and Testing Devices: Score - 0
    Network Cables: Score - 0

  • 完成模块2测验时显示:

    Fundamentals of Networking: Score - 0
    Network Tools and Testing Devices: Score - 10
    Network Cables: Score - 0

  • 完成模块3测验时显示:

    Fundamentals of Networking: Score - 0
    Network Tools and Testing Devices: Score - 0
    Network Cables: Score - 7

期望效果:

  • 完成模块1测验时显示上述第一个结果;
  • 完成模块2测验时保留模块1得分:

    Fundamentals of Networking: Score - 10
    Network Tools and Testing Devices: Score - 10
    Network Cables: Score - 0

  • 完成模块3测验时保留前两个模块得分:

    Fundamentals of Networking: Score - 10
    Network Tools and Testing Devices: Score - 10
    Network Cables: Score - 7

现有代码

@app.route("/submit", methods=["POST", "GET"])
def submit_quiz():
    global email
    global quiz_attempts

    users = []
    attempts = []
    scores = {'Fundamentals of Networking': 0, 'Network Tools and Testing Devices': 0, 'Network Cables': 0}
    quiz_files = ["questions1.txt", "questions2.txt", "questions3.txt"]

    for idx, quiz_file in enumerate(quiz_files):
        quiz = []
        questions_file = open(quiz_file, "r")
        questions = questions_file.read().splitlines()
        questions_file.close()
        number = 0

        for number, question in enumerate(questions):
            question_object = create_question_object(question, number)
            quiz.append(question_object)

        for idx in range(0, len(quiz)):
            mcq = "mcq" + str(idx + 1)
            attempts.append(request.form.get(mcq))

        print("Length of quiz:", len(quiz))
        print("Length of attempts:", len(attempts))

        if quiz_file == "questions1.txt":
            quiz_name = "Fundamentals of Networking"
        elif quiz_file == "questions2.txt":
            quiz_name = "Network Tools and Testing Devices"
        else:
            quiz_name = "Network Cables"

        for idx in range(0, len(quiz)):
            if quiz[idx].correct == attempts[idx]:
                scores[quiz_name] += 1

    users_data_file = open("users_data.txt", "r")
    users = users_data_file.read().splitlines()
    users_data_file.close()

    for idx in range(0, len(users)):
        if email == get_field(users[idx], 1):
            users[idx] = (
                str(get_field(users[idx], 0))
                + ","
                + str(get_field(users[idx], 1))
                + ","
                + str(get_field(users[idx], 2))
                + ","
                + str(scores["Fundamentals of Networking"])
                + ","
                + str(scores["Network Tools and Testing Devices"])
                + ","
                + str(scores["Network Cables"])
            )

    user_data_file = open("users_data.txt", "w")
    for user in users:
        print(user, file=user_data_file, sep="\n")
    user_data_file.close()

    return render_template("user.html")

@app.route("/show", methods=["POST", "GET"])
def results():
    global email
    users = []

    users_data_file = open("users_data.txt", "r")
    users = users_data_file.read().splitlines()
    users_data_file.close()

    # Initialize dictionaries to store scores for each quiz
    scores = {
        'Fundamentals of Networking': 0,
        'Network Tools and Testing Devices': 0,
        'Network Cables': 0
    }

    for user in users:
        # Check if the user's email matches
        if email == get_field(user, 1):
            # Update scores for each quiz from the user's data
            scores['Fundamentals of Networking'] = get_field(user, 3)
            scores['Network Tools and Testing Devices'] = get_field(user, 4)
            scores['Network Cables'] = get_field(user, 5)

    return render_template("result.html", scores=scores)

问题原因与修复方案

核心问题

  1. 得分初始化错误:每次提交测验时,scores字典都被硬编码为全0,没有读取用户已保存的历史得分,导致未参与的模块得分被强制重置。
  2. 无效遍历所有测验:代码循环处理了三个测验文件,但用户每次只提交一个模块的测验,其他模块的答题数据不存在,会错误计算出0分覆盖历史得分。

修复步骤

  1. 优先读取历史得分:在计算当前测验得分前,从users_data.txt中加载该用户的已有得分,初始化scores字典。
  2. 仅处理当前提交的测验:通过前端传递的标识(如隐藏表单字段)判断用户提交的模块,只处理对应测验文件,避免无效计算。

修改后的代码

@app.route("/submit", methods=["POST", "GET"])
def submit_quiz():
    global email

    users = []
    attempts = []
    # 初始化得分字典,先加载用户历史数据
    scores = {
        'Fundamentals of Networking': 0,
        'Network Tools and Testing Devices': 0,
        'Network Cables': 0
    }

    # 读取用户数据,获取当前用户的历史得分
    users_data_file = open("users_data.txt", "r")
    users = users_data_file.read().splitlines()
    users_data_file.close()

    for user in users:
        if email == get_field(user, 1):
            # 转换为整数避免字符串计算错误
            scores['Fundamentals of Networking'] = int(get_field(user, 3))
            scores['Network Tools and Testing Devices'] = int(get_field(user, 4))
            scores['Network Cables'] = int(get_field(user, 5))
            break

    # 获取前端传递的当前测验文件标识(需要在表单中添加隐藏字段)
    quiz_file = request.form.get('quiz_file')
    if not quiz_file:
        return render_template("user.html")

    # 仅处理当前提交的测验
    quiz = []
    questions_file = open(quiz_file, "r")
    questions = questions_file.read().splitlines()
    questions_file.close()

    for number, question in enumerate(questions):
        question_object = create_question_object(question, number)
        quiz.append(question_object)

    for idx in range(len(quiz)):
        mcq = "mcq" + str(idx + 1)
        attempts.append(request.form.get(mcq))

    print("Length of quiz:", len(quiz))
    print("Length of attempts:", len(attempts))

    # 确定当前测验名称
    if quiz_file == "questions1.txt":
        quiz_name = "Fundamentals of Networking"
    elif quiz_file == "questions2.txt":
        quiz_name = "Network Tools and Testing Devices"
    else:
        quiz_name = "Network Cables"

    # 计算当前测验得分
    current_score = 0
    for idx in range(len(quiz)):
        if quiz[idx].correct == attempts[idx]:
            current_score += 1
    # 替换为本次得分,若需保留最高分可改为max(scores[quiz_name], current_score)
    scores[quiz_name] = current_score

    # 更新用户数据
    for idx in range(len(users)):
        if email == get_field(users[idx], 1):
            users[idx] = (
                str(get_field(users[idx], 0))
                + ","
                + str(get_field(users[idx], 1))
                + ","
                + str(get_field(users[idx], 2))
                + ","
                + str(scores["Fundamentals of Networking"])
                + ","
                + str(scores["Network Tools and Testing Devices"])
                + ","
                + str(scores["Network Cables"])
            )

    user_data_file = open("users_data.txt", "w")
    for user in users:
        print(user, file=user_data_file, sep="\n")
    user_data_file.close()

    return render_template("user.html")

@app.route("/show", methods=["POST", "GET"])
def results():
    global email
    users = []

    users_data_file = open("users_data.txt", "r")
    users = users_data_file.read().splitlines()
    users_data_file.close()

    scores = {
        'Fundamentals of Networking': 0,
        'Network Tools and Testing Devices': 0,
        'Network Cables': 0
    }

    for user in users:
        if email == get_field(user, 1):
            scores['Fundamentals of Networking'] = int(get_field(user, 3))
            scores['Network Tools and Testing Devices'] = int(get_field(user, 4))
            scores['Network Cables'] = int(get_field(user, 5))
            break

    return render_template("result.html", scores=scores)

额外说明

  • 前端需要在测验表单中添加隐藏字段,例如提交模块1时添加:<input type="hidden" name="quiz_file" value="questions1.txt">,不同模块对应修改value值。
  • 若需要支持用户重测模块时保留最高分,可将scores[quiz_name] = current_score改为scores[quiz_name] = max(scores[quiz_name], current_score)。

内容的提问来源于stack exchange,提问作者win

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:17:33