# Write a function to open and read a file named StarWars.csv # from https://storage.googleapis.com/cs1111/examples/file/StarWars.csv # The function will return a dictionary containing # the number of fans and the total number of respondents. # That is, { 'number_fans': 552, 'total_respondents':1186 } # There are many columns (or fields) for each line. # You only need the following columns to complete this exercise: # RespondentID (column 0) # Have you seen any of the 6 films in the Star Wars franchise? (column 1) # -- possible value "Yes" or "No" # Do you consider yourself to be a fan of the Star Wars film franchise? (column 2) # -- possible value "Yes" or "No" # Note: There are exactly 2 header lines. ## this solution reads a file from the internet (via a URL) # import a library for opening URL import urllib.request # get the url, open # read each line # split into columns # look at columns -- index 0,1,2 # increment number responses # check index 2 if it "yes" # then add 1 to number of fans # need number of fans def count_number_fans(url): number_of_fans = 0 number_responses = 0 number_line_skip = 2 stream = urllib.request.urlopen(url) for line in stream: if number_line_skip > 0: number_line_skip -= 1 else: # processing data number_responses += 1 decoded_line = line.decode('UTF-8') columns = decoded_line.split(",") if columns[2].lower() == 'yes': # 'YES' 'yes' 'Yes' number_of_fans +=1 starwars_dict = {} starwars_dict['number_fans'] = number_of_fans starwars_dict['number_responses'] = number_responses return starwars_dict print(count_number_fans('https://storage.googleapis.com/cs1111/practice/StarWars.csv'))