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

编程作业:从格式化试题文本文件提取指定要素(禁用特定语法)

问题描述
  • 需编写代码接收命令行传入的文本文件名,读取格式固定的考试试题,提取以下要素:题型、题目内容、所有可选答案、预期答案、答题分值
  • 文本文件包含多道试题,以空行分隔
  • 禁止使用关键字/内置函数:for, in(成员检测), global, lambda, nonlocal, all(), any(), dir(), eval(), enumerate(), filter(), globals(), locals(), map()

试题格式示例:

Question - Multiple
Select all the animals that are mammals:
Possible Answers: 
A. whale
B. dog
C. fish
D. frog
Expected Answer: A, B
Marks: 2
解决方案

核心思路

  1. 读取文件内容后,按连续空行分割成独立的试题块
  2. 对每个试题块,通过字符串分割、截取、清理操作提取各要素,全程用while循环替代for遍历
  3. 用字符串方法(split(), strip(), startswith()等)定位关键标记行,提取对应内容

实现代码

import sys

def extract_question_details(question_block):
    details = {}
    # 分割成单行并过滤空行
    lines = question_block.split('\n')
    cleaned_lines = []
    idx = 0
    while idx < len(lines):
        line = lines[idx].strip()
        if line:
            cleaned_lines.append(line)
        idx += 1
    
    # 提取题型
    idx = 0
    while idx < len(cleaned_lines):
        line = cleaned_lines[idx]
        if line.startswith("Question - "):
            details['type'] = line.split("Question - ")[1].strip()
            break
        idx += 1
    
    # 提取题目内容(题型行之后,到Possible Answers之前)
    idx += 1
    question_text = []
    while idx < len(cleaned_lines):
        line = cleaned_lines[idx]
        if line.startswith("Possible Answers:"):
            break
        question_text.append(line)
        idx += 1
    details['question'] = ' '.join(question_text).strip()
    
    # 提取可选答案(Possible Answers之后,到Expected Answer之前)
    idx += 1
    answers = {}
    while idx < len(cleaned_lines):
        line = cleaned_lines[idx]
        if line.startswith("Expected Answer:"):
            break
        parts = line.split('. ', 1)
        if len(parts) == 2:
            answers[parts[0].strip()] = parts[1].strip()
        idx += 1
    details['possible_answers'] = answers
    
    # 提取预期答案
    line = cleaned_lines[idx]
    ans_part = line.split("Expected Answer: ")[1].strip()
    ans_list = ans_part.split(',')
    cleaned_ans = []
    idx_ans = 0
    while idx_ans < len(ans_list):
        cleaned_ans.append(ans_list[idx_ans].strip())
        idx_ans += 1
    details['expected_answer'] = cleaned_ans
    
    # 提取分值
    idx += 1
    line = cleaned_lines[idx]
    details['marks'] = int(line.split("Marks: ")[1].strip())
    
    return details

def main():
    if len(sys.argv) < 2:
        print("请传入试题文件名作为命令行参数")
        return
    
    filename = sys.argv[1]
    try:
        with open(filename, 'r') as fobj:
            content = fobj.read()
        
        # 分割试题块,过滤无效空块
        question_blocks = content.split('\n\n')
        cleaned_blocks = []
        idx = 0
        while idx < len(question_blocks):
            block = question_blocks[idx].strip()
            if block:
                cleaned_blocks.append(block)
            idx += 1
        
        # 处理所有试题块
        questions = []
        idx = 0
        while idx < len(cleaned_blocks):
            q_details = extract_question_details(cleaned_blocks[idx])
            questions.append(q_details)
            idx += 1
        
        # 输出提取结果(可替换为答题逻辑)
        idx = 0
        while idx < len(questions):
            print(f"第{idx+1}题:")
            print(f"题型:{questions[idx]['type']}")
            print(f"题目:{questions[idx]['question']}")
            print("可选答案:")
            ans_keys = list(questions[idx]['possible_answers'].keys())
            k_idx = 0
            while k_idx < len(ans_keys):
                key = ans_keys[k_idx]
                print(f"  {key}. {questions[idx]['possible_answers'][key]}")
                k_idx += 1
            print(f"预期答案:{', '.join(questions[idx]['expected_answer'])}")
            print(f"分值:{questions[idx]['marks']}\n")
            idx += 1
    except FileNotFoundError:
        print(f"未找到文件:{filename}")

if __name__ == "__main__":
    main()

代码说明

  • 用while循环配合索引遍历列表,规避for关键字
  • 通过startswith()定位关键标记行,替代in成员检测
  • 所有字符串处理均使用基础分割、清理方法,未使用禁用函数
  • 自动过滤空行和无效内容,确保试题块的完整性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:58:18