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

Python患者管理程序remove功能异常:已添加患者无法删除

问题:Remove命令无法找到已添加的患者

实现了从txt文件读取命令(create/remove/list)并输出结果到另一个文件的功能:

  • create:添加患者到列表
  • remove:删除指定患者
  • list:展示所有患者

问题现象:通过create成功添加患者后,list能正常显示,但执行remove命令时始终提示Patient [姓名] cannot be removed due to absence。

错误原因

  1. 存储与匹配逻辑不匹配:
    你在frameList中存储的是完整的create命令列表(比如['create', 'Ateş,', '0.99', ...]),但执行remove时,你用当前的remove命令列表(['remove', 'Ateş'])去frameList中查找,这两个列表完全不同,所以永远匹配失败。
  2. 输入分割的格式问题:
    输入文件中create命令的姓名后面带逗号(比如Ateş,),split后姓名字段是'Ateş,',但remove命令中的姓名是'Ateş',即使按姓名匹配也会因为逗号不匹配找不到。

修复后的代码

input_file = open('doctors_aid_inputs.txt', 'r')
output_file = open('doctors_aid_outputs.txt', 'w')
read = input_file.readlines()

# 用字典存储患者,键为患者姓名(去除逗号),值为患者完整信息
patients = {}

for line in read:
    # 先去除换行符,再处理逗号:把所有逗号替换成空格,再分割
    cleaned_line = line.strip().replace(',', '')
    command = cleaned_line.split()
    
    if command[0] == 'create':
        # 提取患者信息,此时姓名已经没有逗号
        patient_name = command[1]
        accuracy = command[2]
        disease_name = command[3]
        incidence = command[4]
        treatment = command[5]
        risk = command[6]
        
        if patient_name not in patients:
            # 存储患者信息为列表
            patients[patient_name] = [patient_name, accuracy, disease_name, incidence, treatment, risk]
            output_file.write(f'Patient {patient_name} is recorded.\n')
        else:
            output_file.write(f'Patient {patient_name} cannot be created due to duplication.\n')
    
    elif command[0] == 'remove':
        patient_name = command[1]
        if patient_name in patients:
            del patients[patient_name]
            output_file.write(f'Patient {patient_name} is removed.\n')
        else:
            output_file.write(f'Patient {patient_name} cannot be removed due to absence.\n')
    
    elif command[0] == 'list':
        # 打印表头
        output_file.write('Patient           Diagnosis         Disease           Disease            Treatment              Treatment          \n')
        output_file.write('Name              Accuracy          Name              Incidence          Type                   Risk               \n')
        output_file.write('-------------------------------------------------------------------------------------------------------------------\n')
        # 遍历所有患者信息
        for info in patients.values():
            # 按格式输出每个字段,补空格对齐
            for item in info:
                output_file.write(f'{item}{" "*(18 - len(item))}')
            output_file.write('\n')

# 关闭文件
input_file.close()
output_file.close()

关键修复点

  • 改用字典patients存储患者,以无逗号的姓名为键,方便快速查找和删除
  • 处理输入时先去除逗号再分割,避免姓名带逗号导致的匹配失败
  • remove命令直接通过姓名查找字典,逻辑更清晰高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:55:27