Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Reproduce Perl exercise 4 in Python . Save it as roster_dictionary.py. Include t

ID: 3848896 • Letter: R

Question

Reproduce Perl exercise 4 in Python. Save it as roster_dictionary.py. Include the source code in python_assignment.txt.

Perl exercise 4 is as follows:

# perlex4.pl - Read and process class roster using hash

while ($studentline = <>) {
   ($last, $first, $id) = split /s*, s*/,$studentline;
       # Use "*s*,s*" as field delimiter to split $studentline
       # into last, first and id fields.
       # "s*" = 0 or more white space chars
      
   # Insert student into %roster hash with $id as key
   chomp($id);
   $roster{$id} = "$last, $first";
       # Value is last name ,first name as a string
}

# Print the roster hash
foreach $id (sort keys %roster) {
   print "$id, $roster{$id} "; # print key and value (ellen:sorted by student id)
}

Explanation / Answer

Code:
#!/usr/bin/python

import sys
import re

# script name: roster_dictionary.py

def main():
# declaring and initializing studentline array
studentline = []
  
# the if else code below is equivalent to diamond operator <> in perl
# checking if command line argument is 1. that means there is only one filename
if len(sys.argv) == 1:
# reading entire file contents to studentline array
studentline = sys.stdin.readlines()
else:
# if there are more than one filename then read each file
for file in sys.argv[1:]:
with open(file) as fp:
# adding each file content to studentline array
studentline.extend(fp.readlines())
fp.close()

# declaring and initializing roster dictionary
roster = {}
# iterating through each element of studentline array
for each_line in studentline:
# removing new line from each line
each_line = each_line.strip()
# getting last, first and id from the line
last, first, id = re.split('s*, s*', each_line)
# storing last first names as value and id as key in roster dictionary
roster[id] = last + "," + first

# iterating through each key in roster dictionary and displaying the contents   
for each_item in roster:
print each_item, roster[each_item]
  
  
if __name__=='__main__':
main()


Execution and output:
I have created input file student.txt which looks like below.

Unix Terminal> cat student.txt
krishna , Vijay , 101
Amulya , Varshitha , 102
Madhavi , Latha , 103
Lahari , Samhitha , 104
Executing the script by passing student.txt file as command line input
Unix Terminal> python roster_dictionary.py student.txt
102 Amulya,Varshitha
103 Madhavi,Latha
101 krishna,Vijay
104 Lahari,Samhitha
Unix Terminal>

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote