Question
Please see my code, I am getting the following error on line 87 and probably line 89 after that. I have left the prompt I
Please see my code, I am getting the following error on line 87 and probably line 89 after that. I have left the prompt I am working on below my code. Please help!
AttributeError: 'Repository' object has no attribute 'student'
import os
from HW08 import file_reader
from typing import List, Iterator, Tuple, DefaultDict, Dict
from collections import defaultdict
from prettytable import PrettyTable
class Student:
"""holds all of the details of a student, including a dict to
store the classes taken and the grade where the course is the key and the grade is the value."""
student_field_names: List[str] = ["CWID", "Name", "Completed Courses"]
def __init__(self, cwid: int, name: str, major: str) -> None:
self._cwid: str = cwid
self._name: str = name
self._major: str = major
self._courses: Dict[str, str] = dict()
def course_grade(self, course: str, grade: str) -> None:
self._courses[course] = grade
def student_information(self) -> Tuple[str, str, List[str]]:
return [self._cwid, self._name, sorted(self._courses.keys())]
class Instructor:
"""holds all of the details of an instructor, including a defaultdict(int) to
store the names of the courses taught along with the number of students who have taken the course.
"""
instructor_field_names: List[str] = ["CWID", "Name", "Dept", "Courses", "Students"]
def __init__(self, cwid: int, name: str, department: str) -> None:
self._cwid: str = cwid
self._name: str = name
self._department: str = department
self._courses: DefaultDict[str, int] = defaultdict(int)
def add_students(self, course: str) -> None:
self._courses[course] += 1
def instructor_information(self) -> Iterator[Tuple[str, str, str, str, int]]:
for course, students in self._courses.items():
yield [self._cwid, self._name, self._department, course, students]
class Repository:
"""Includes a container for all students, Includes a container for all instructors
__init__(self, dir_path) specifies a directory path where to find the students.txt, instructors.txt, and grades.txt files.
"""
def __init__(self, dir_path: str, tables: bool = True) -> None:
self._dir_path: str = dir_path
self._students_dict: Dict[str, Student] = dict()
self._instructors_dict: Dict[str, Instructor] = dict()
try:
self._get_students(os.path.join(dir_path, "students.txt"))
self._get_instructors(os.path.join(dir_path, "instructors.txt"))
self._get_grades(os.path.join(dir_path, "grades.txt"))
except FileNotFoundError:
raise FileNotFoundError("Error, cannot find file")
except ValueError as e:
print(e)
else:
if tables:
print("Student Information")
print(self.student_pt())
print("Instructor Information")
print(self.instructor_pt())
def _get_students(self, path: str) -> None:
try:
students_information: Iterator(Tuple[str]) = file_reader(path, 3, sep = "\t", header = False)
for cwid, name, major in students_information:
self._students_dict[cwid] = Student(cwid, name, major)
except ValueError as e:
raise ValueError(e)
def _get_instructors(self, path: str) -> None:
try:
instructors_information: Iterator(Tuple[str]) = file_reader(path, 3, sep = "\t", header = False)
for cwid, name, department in instructors_information:
self._instructors_dict[cwid] = Instructor(cwid, name, department)
except ValueError as e:
raise ValueError(e)
def _get_grades(self, path: str) -> None:
grades: Iterator(Tuple[str]) = file_reader(path, 4, sep="\t", header = False)
for st_cwid, course, grade, inst_cwid in grades:
if st_cwid in self._students_dict:
self._students_dict[st_cwid].course_grade(course, grade)
else:
print(f"student grade {st_cwid}")
if inst_cwid in self._instructors_dict:
self._instructors_dict[inst_cwid].add_students(course)
else:
print(f"instrutor grade {inst_cwid}")
def student_table(self) -> None:
prettytable: PrettyTable = PrettyTable(field_names=Student.st_field_names)
for student in self._students_dict.values():
prettytable.add_row(student.st_data())
return prettytable
def instructor_table(self) -> None:
prettytable: PrettyTable = PrettyTable(field_names=Instructor.inst_field_names)
for instructor in self._instructors_dict.values():
for row in instructor.inst_data():
prettytable.add_row(row)
return prettytable
def main() -> None:
File: Repository = Repository("D:\Documents\School\Stevens\810", True)
if __name__ == "__main__":
main()
HW08 File Reader
def file_reader(path, fields, sep=',', header=False):
try:
with open(path) as infile:
# check first if header is True
if header:
first_line = infile.readline()# Read the first line
l = len(first_line.split(sep))# get the number of fields using the function len
if l != fields:# Raise an error if
print("Provided fields (%d) does not match the header's number of fields (%d)" % (fields, l))
raise ValueError
line_num = 2# start at line 2 if we have a header
else:
line_num = 1# start at line 1 otherwise
for line in infile:
ln = line.split(sep)
l = len(ln)
if l == fields: # Check if this line's number of fields matches the expected number.
yield ln
else: # Raise an exception that shows the difference in field numbers and the line where it occured
print("ValueError: '%s' has %d fields on line %d but expected %d" % (path, l, line_num, fields))
raise ValueError
line_num += 1# Increment line_num as we loop through lines
except FileNotFoundError:# Python will
print("Cannot find %s" % path)
raise FileNotFoundError
Prompt:
Part1:
You've been hired by Stevens Institute of Technology to make adata repository of courses, students, and instructors.The system will be used to help students track their required courses, the courses they have successfully completed, their grades,GPA, etc.The system will also be used by faculty advisors to help students tocreate study plans.We will continue to add new features tothis solution over the coming weeksso you'll want to think carefully about a good design and implementation.
Your assignment this week is to begin to build the framework for your project and summarize student and instructor data.You'll need to download three ASCII, tab separated,data files:
1.students.txt
- Provides information about each student
- Each line has the format: CWID\tName\tMajor (where \t is the
character)
2.instructors.txt
- Provides information about eachinstructor
- Each line has the format: CWID\tName\tDepartment (where \t is the
character)
3.grades.txt
- Specifies the student CWID, course, and grade for that course, and the instructor CWID
- Each line has the format: Student CWID\tCourse\tLetterGrade\tInstructor CWID
Here are the text files:
Student:
10103 Baldwin, C SFEN
10115 Wyatt, X SFEN
10172 Forbes, I SFEN
10175 Erickson, D SFEN
10183 Chapman, O SFEN
11399 Cordova, I SYEN
11461 Wright, U SYEN
11658 Kelly, P SYEN
11714 Morton, A SYEN
11788 Fuller, E SYEN
Instructor:
98765 Einstein, A SFEN
98764 Feynman, R SFEN
98763 Newton, I SFEN
98762 Hawking, S SYEN
98761 Edison, A SYEN
98760 Darwin, C SYEN
Grades:
10103 SSW 567 A 98765
10103 SSW 564 A- 98764
10103 SSW 687 B 98764
10103 CS 501 B 98764
10115 SSW 567 A 98765
10115 SSW 564 B+ 98764
10115 SSW 687 A 98764
10115 CS 545 A 98764
10172 SSW 555 A 98763
10172 SSW 567 A- 98765
10175 SSW 567 A 98765
10175 SSW 564 A 98764
10175 SSW 687 B- 98764
10183 SSW 689 A 98763
11399 SSW 540 B 98765
11461 SYS 800 A 98760
11461 SYS 750 A- 98760
11461 SYS 611 A 98760
11658 SSW 540 F 98765
11714 SYS 611 A 98760
11714 SYS 645 C 98760
11788 SSW 540 A 98765
Your assignment is to read the data from each of the three files and store it in a collection of classes that are easy to process to meet the following requirements:
- Your solution should allow a single program to create repositories for different sets of data files, e.g. one set of files for Stevens, another for Columbia University, and a third for NYU.Each university will have different directories of data files.Hint: you should define a class to hold all of the information for a specific university.
- You may hard code the names of each of the required data file names within a directory, e.g. "students.txt", "instructors.txt", and "grades.txt".Your solution should accept the directory path where the three data files exist so you can easily create multiple sets of input files for testing.I'll test your solution against multiple data directories representing different universities so be sure your solution allows me to easily run against multiple data directories.
- Printwarning messages if the input file doesn't exist or doesn't meet the expected format.
- Printwarning messages if the grades file includes an unknown instructor or student
- Use PrettyTable to generate and print a summary table of all of the students with their CWID, name, and asortedlist of the courses they've taken (as specified in the grades.txt file).
- Use PrettyTable to generate and print a summary table of each of the instructors who taught at least one course with their CWID, name, department, the course they've taught, and the number of students in each class.
- Implement automated tests to verify that the data in the prettytables matches the data from the input data files.
- Youdo NOTneed to implement automated tests to catch all possible error conditions but your program should print relevant error messages when invalid or missing data is detected.
- Your solution SHOULD print error messages and warnings to the user about inconsistent or bad data, e.g. a data file with the wrong number of fields or a grade for an unknown student or instructor.
Here's an example of theStudent and Instructor summary tables. Note that the completed courses are sorted alphabetically:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started