如何从 python 中的文件中正确读取和存储每一行,我也在使用 maxheap 类?

问题描述 投票:0回答:0

输入文件

ARRIVE John Gibbons 39 sleep_deprivation 2
ARRIVE C.S. Student 19 coffee_overdose 6
ARRIVE Grigori Rasputin 47 everything 9
COUNT
NEXT
TREAT
NEXT
TREAT
COUNT

输出我试图得到

There are 3 patients waiting.

Next patient:
Name: Rasputin, Grigori.
Age: 47
Suffers from: everything
Illness severity: 9

Next patient:
Name: Student, C.S.
Age: 19
Suffers from: coffee_overdose
Illness severity: 6

There is 1 patient waiting.

我的输出

first_name = line\[1\]
IndexError: list index out of range

我的班级有 run 方法

from maxheap import MaxHeap
from patient import Patient

class Hospital:
def __init__(self):
self.queue = MaxHeap()

    def arrive(self, first_name, last_name, age, illness, severity):
        patient = Patient(first_name, last_name, age, illness, severity)
        self.queue.insert(patient)
    
    def next(self):
        next_patient = self.queue.extract_max()
        if next_patient:
            print("Next patient:")
            print("Name: {} {}".format(next_patient.last_name, next_patient.first_name))
            print("Age:", next_patient.age)
            print("Suffers from:", next_patient.illness)
            print("Illness severity:", next_patient.severity)
        else:
            print("No patients waiting.")
    
    def treat(self):
        if self.queue != None:
            self.queue.heapify(0)
        else:
            print("No more patients to be treated.")
    
    def count(self):
        print("There are {} patient(s) waiting.".format(len(self.queue.heap)))
    
    def run(self, filename):
        with open(filename, 'r') as file:
            for line in file:
                line = line.strip().split()
                first_name = line[1]
                last_name = line[2]
                age = int(line[3])
                illness = line[4]
                severity = int(line[5])
                if line[0] == 'ARRIVE':
                    self.arrive(first_name, last_name, age, illness, severity)
                elif line[0] == 'NEXT':
                    self.next()
                elif line[0] == 'TREAT':
                    self.treat()
                elif line[0] == 'COUNT':
                    self.count()
python c++ file readfile max-heap
© www.soinside.com 2019 - 2024. All rights reserved.