-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
206 lines (166 loc) · 8.05 KB
/
main.py
1
#Automated Election Poll Analysis Results#Python script to create an election poll analysis of results#Election poll data from election_data.csv#Reads in csv file and writes the analysis data results to a text file 'analysis.txt' in the 'analysis' folder#ASSUMPTIONS: file does not need to be sorted or cleaned, folder structure as outlined in Readme.md# all data is consistent in csv file, code finds the relative paths# Python 3.8.8#Dependenciesimport osimport csvelection_data = []#paths to filescsvpath_election = os.path.join('Resources','election_data.csv')txtpath = os.path.join('analysis','analysis.txt')def csvElectionData(csvpath_election): #function to get the election data from the csv file #calculating: Number of months, total $, average $ amt., the month that had the greatest increase/decrease and that amount. #inputs the csvpath_finances as the csv file path #returns the data in a list ttl_votes = 0 ind_votes = 0 ind_index = 0 vote_summary = [] winner = '' result = [] #check if the csv file is there if os.path.exists(csvpath_election): #open a the csv file with open(csvpath_election,'r', newline='', encoding='utf-8') as csvfile: #create a reader object csv_reader= csv.reader(csvfile, delimiter=',') #read in header header = next(csv_reader) #check if file is not empty if header != None: #iterate over each row after header for line in csv_reader: #'check if name is not already in vote_summary' if line[2] not in vote_summary: #name vote_summary.append(line[2]) # add a holder for percentage of votes as zero vote_summary.append(0) #add first vote vote_summary.append(1) else: #have name already, add another vote #findividual index ind_index = vote_summary.index(line[2]) #get the votes have ind_votes = vote_summary[ind_index + 2] #substitute votes have to old vote + 1 vote_summary[ind_index + 2] = ind_votes + 1 #recalculate total votes ttl_votes += 1 ind_votes = 0 #get greatest vote from the vote summary max_votes = max([i for i in vote_summary[2::3]]) #get the individuals name index at that number ind_index = vote_summary.index(max_votes) -2 #store the winner winner = vote_summary[ind_index] #recalculate the vote percentage from 0 originally #replace with actual percentage of votes now that have a total for index, item in enumerate(vote_summary): if index > 0 and index % 3 == 2: val =round(item/ttl_votes * 100,3) vote_summary[index - 1] = val #add results to a list result.append(ttl_votes) result.append(winner) #list of candisate name, % votes, number of votes result.append(vote_summary) #no header, no information in fie, should have one else: print("No header found, this may not be the correct file. It may be empty") #no file to read else: print("Either the file is missing or the file is not readable.") #return the data return result def writeData(election_data,txtpath, **kwargs): #function creates a file if it is not there, then append data (allows for several runs with a file of the same name) #Appends to a text file: the polling data in the list, total votes, candidates: name,% of votes,votes aquired, winner #inputs: the election_data as a list, textpath as the text file path for the results # kwargs as this can be run to print to file(f), screen(s) or both by inputting 2 kwarg values #Out: Writes results to a text file (f): in analysis folder, called analysis.txt # Prints to screen (s), # Set with kwargs so user can set to print one option they want or both for key, value in kwargs.items(): if value == 'f': ccount = 0 #to count each candidate stats as loop list if not os.path.exists(txtpath): with open(txtpath, "w", newline="", encoding='utf-8') as f: pass if(os.path.exists(txtpath)): with open(txtpath, "a", newline="") as f: #appends to end of file, add an extra line f.write("\n") # Write the title f.write("Election Results\n") f.write("-" * 30 + "\n") #Print data f.write(f"Total Votes: {election_data[0]}\n") f.write("-" * 30 + "\n") #loop through the list of candidate info, naem, vote percentage , and vote count #every third item is a new candidate: thus a new line , reset count for each in election_data[2]: if ccount == 0: #write the name f.write(each + ":") elif ccount == 1: #write the percentage of votes f.write(" " + "{0:.3f}".format(each) + "%") elif ccount == 2: #write the njmber of votes for candidate f.write(" (" + str(each) + ")\n") if ccount < 2: ccount += 1 else: ccount = 0 f.write("-" * 30 + "\n") f.write(f"Winner: {election_data[1]}\n") f.write("-" * 30 + "\n\n") elif value == 's': ccount = 0 print("Election Results\n") print("-" * 10) #Print data print(f"Total Votes: {election_data[0]}\n") print("-" * 10) ind_stats = "" for each in election_data[2]: if ccount == 0: #write the name ind_stats = each + ":" elif ccount == 1: #write the percentage of votes ind_stats += " " + "{0:.3f}".format(each) + "%" #f.write(" " + "{0:.3f}".format(each) + "%") elif ccount == 2: #write the njmber of votes for candidate ind_stats += " (" + str(each) + ")" #f.write(" (" + str(each) + ")\n") if ccount < 2: ccount += 1 else: print(ind_stats) ccount = 0 ind_stats = "" print("-" * 10) print(f"Winner: {election_data[1]}\n") print("-" * 10) else: print("A valid print option was not entered.") #call the function to get the election poll data returnedelection_data = csvElectionData(csvpath_election) #check for dataif len(election_data): #write the election poll analysis to a text file #no default value for kwargs, so set to output to file(f) and screen(s) writeData(election_data,txtpath, val1 = 'f', val2 ='s') election_data.clear() print("Your election poll analysis is complete.") else: print("Your election poll data is not there.")