In: Computer Science
Please use python3
Create the function team_average which has the following header
def team_average(filename):
This function will return the average number of games won by the Red Sox from a text file with entries like this
2011-07-02 Red Sox @ Astros Win 7-5 2011-07-03 Red Sox @ Astros Win 2-1 2011-07-04 Red Sox vs Blue Jays Loss 7-9
This function should create a file object for the file whose
name is given by the parameter filename.
If the file cannot be opened, use a try/except statement to print
an error message and don't do any further work on the file.
The function will count the number of lines and the number of games
the Red Sox won and use these values to compute the average games
won by the team.
This average should be expressed as an integer.
Test Code
Your hw2.py file must contain the following test code at the bottom of the file
team_average('xxxxxxx') print(team_average('red_sox.txt'))
For this test code to work, you must copy into your hw2
directory the file red_sox.txt from
/home/ghoffman/course_files/it117_files.
To do this go to your hw2 directory and run cp
/home/ghoffman/course_files/it117_files/red_sox.txt .
Suggestions
Write this program in a step-by-step fashion using the technique
of incremental development.
In other words, write a bit of code, test it, make whatever changes
you need to get it working, and go on to the next step.
Cannot open xxxxxxx None
Output
When you run the completed script, you should see
Error: Unable to open xxxxxxx 76
def team_average(fileName): try: matchesWon = 0 totalMatches = 0 with open(fileName, 'r') as file: # file opened for line in file: # ging through each line totalMatches += 1 # number of lines is number of matches tokens = line.split() # splitting each line by spaces if tokens[-2].lower() == 'win': # at -2 index, result of match is stored #index -2 is counted fro, right,so last position is -1, second last position is -2 matchesWon += 1 # if result is win, increment counter return int(matchesWon * 100 / totalMatches) # integer percent returned except IOError: print('Error : Unable to open', fileName) team_average('xxxx') print(team_average('red_sox.txt'))