How to print a certain cell under a specific condition - python

import csv
from statistics import mean
def analyze(entries):
print(f'first entry: {entries[0]}')
with open("reddit_vm.csv", "r", encoding='UTF-8', errors="ignore") as input:
entries = [(e['id'], int(e['score']), int(e['comms_num']), e['title']) for e in csv.DictReader(input)]
avgScore = analyze(entries)
# highest score / title for that post
highScore = max(score) # Find the highest score
print("\nHighest score:")
print(highScore)
title = []
title = [i[3] for i in entries]
print("\nTitle for the Highest Scores:")
selected_column = [title, score]
highTitle = title(score == highScore)
print(highTitle)
This is some portion of my code in Python.
I need to find the title for the highest scores, and print it.
it is 'I would rage if this was handed to me...'.
So the expected output should be like this:
Title for the Highest Scores:
I would rage if this was handed to me...
This is the excel file: https://drive.google.com/file/d/1glhNHkzKwHVqwuWbS8ajiNJR3H94Xw4W/view?usp=sharing

I've downloaded your csv and corrected your code
I've written comments for you to understand your errors
import csv
from statistics import mean
def analyze(entries):
print(f'first entry: {entries[0]}')
with open("reddit_vm.csv", "r", encoding='UTF-8', errors="ignore") as input:
entries = [(e['id'], int(e['score']), int(e['comms_num']), e['title']) for e in csv.DictReader(input)]
avgScore = analyze(entries)
# highest score / title for that post
# highScore = max(score) # Find the highest score
#first error: what 'score'? what is this? you need to assign a variable first before reference it.
highScore = max([i[1] for i in entries])
print(f'highest score: {highScore}')
# title = []
# what for do you need this line? it's absolute useless
title = [i[3] for i in entries]
#here you've created list `title` with all titles
# print("\nTitle for the Highest Scores:")
# selected_column = [title, score]
#here you create list with two elements
#firs element title list with all titles - so it's 2D list
#sec element non-existing score variable
# highTitle = title(score == highScore)
# in this line you actually run some `title()` function that doesn't exist
# and place bool of `score==highScore` that would be False if `score` would exist as func's arg
#to get this:
# Title for the Highest Scores:
# I would rage if this was handed to me...
# you'd rather use something like this:
entries.sort(key=lambda x:x[1])
#you sort `entries` in a way when the itep with the highest score will be placed as the last element in list. you can use `entries[-1]` to get it
print('Title for the Highest Scores:')
print(entries[-1][3])
it works as you wanted it to

Related

Write map to a csv in python

I am not sure if the title of this is right. I know it is not a list and I am trying to take the results into a dictionary, but it is only adding the last value of my loop.
So I have pasted all my code but I have a question specifically on my candidates loop, where I am trying to get the percentages of votes per candidate. When I print the information it looks like this:
enter image description here
As you can see the 3rd session of the results is showing the candidates and next to them the percentage and the total votes. This results is what I am not sure what is (not a list not a dictionary)
I am trying to write this in my output csv, however after so many ways I always get to write only the last result which is O'Tooley.
I am new at this, so I am not sure first, why even if I save my percentage in a list after each loop, I am still saving only the percentage of O'Tooley. That's why I decided to print after each loop. That was my only way to make sure all the results look as in the picture.
import os
import csv
electiondatapath = os.path.join('../..','gt-atl-data-pt-03-2020-u-c', '03-Python', 'Homework', 'PyPoll', 'Resources', 'election_data.csv')
with open (electiondatapath) as csvelectionfile:
csvreader = csv.reader(csvelectionfile, delimiter=',')
# Read the header row first
csv_header = next(csvelectionfile)
#hold number of rows which will be the total votes
num_rows = 0
#total votes per candidate
totalvotesDic = {}
#list to zip and write to csv
results = []
for row in csvreader:
#total number of votes cast
num_rows += 1
# Check if candidate in the dictionary keys, if is not then add the candidate to the dictionary and count it as one, else sum 1 to the votes
if row[2] not in totalvotesDic.keys():
totalvotesDic[row[2]] = 1
else:
totalvotesDic[row[2]] += 1
print("Election Results")
print("-----------------------")
print(f"Total Votes: {(num_rows)}")
print("-----------------------")
#get the percentage of votes and print result next to candidate and total votes
for candidates in totalvotesDic.keys():
#totalvotesDic[candidates].append("{:.2%}".format(totalvotesDic[candidates] / num_rows))
candidates_info = candidates, "{:.2%}".format(totalvotesDic[candidates] / num_rows), "(", totalvotesDic[candidates], ")"
print(candidates, "{:.2%}".format(totalvotesDic[candidates] / num_rows), "(", totalvotesDic[candidates], ")")
#get the winner out of the candidates
winner = max(totalvotesDic, key=totalvotesDic.get)
print("-----------------------")
print(f"Winner: {(winner)}")
print("-----------------------")
#append to the list to zip
results.append("Election Results")
results.append(f"Total Votes: {(num_rows)}")
results.append(candidates_info)
results.append(f"Winner: {(winner)}")
# zip list together
cleaned_csv = zip(results)
# Set variable for output file
output_file = os.path.join("output_Pypoll.csv")
# Open the output file
with open(output_file, "w") as datafile:
writer = csv.writer(datafile)
# Write in zipped rows
writer.writerows(cleaned_csv)
In each iteration, you created a variable named candidates_info for just one candidate. You need to concatenate strings like this example:
candidates_info = ""
for candidates in totalvotesDic.keys():
candidates_info = '\n'.join([candidates_info, candidates + "{:.2%}".format(totalvotesDic[candidates] / num_rows) + "("+ str(totalvotesDic[candidates])+ ")"])
print(candidates_info)
# prints
# O'Tooley 0.00%(2)
# Someone 30.00%(..)
Also, you don't need keys(). Try this instead:
candidates_info = ""
for candidates, votes in totalvotesDic.items():
candidates_info = '\n'.join([candidates_info, str(candidates) + "{:.2%}".format(votes / num_rows) + "("+ str(votes)+ ")"])

Is there any way to put a single result from a CSV into a variable?

I'm making a program in school where users are quizzed on certain topics and their results are saved into a csv file. I've managed to print off the row with the highest score, but this doesn't look very neat.
with open ('reportForFergusTwo.csv', 'r') as highScore:
highScoreFinder=highScore
valid3=False
for row in highScoreFinder:
if subjectInput in row:
if difficultyInput in row:
if ('10' or '9' or '8' or '7' or '6' or '5' or '4' or '3' or '2' or '1') in row:
valid3=True
print("The highest score for this quiz is:",row)
For example: it says, "The highest score for this quiz is: chemistry,easy,10,Luc16" but I would prefer it to say something like "The highest score for this quiz is: 10" and "This score was achieved by: Luc16", rather than just printing the whole row off, with unnecessary details like what the quiz was on.
My CSV file looks like this:
Subject,Difficulty,Score,Username
language,easy,10,Luc16
chemistry,easy,10,Luc16
maths,easy,9,Luc16
chemistry,easy,5,Eri15
chemistry,easy,6,Waf1
chemistry,easy,0,Eri15
I thought that maybe if I could find a way to take the individual results (the score and username) and put them into their own individual variables, then it would be much easier to present it the way I want, and be able to reference them later on in the function if I need them to be displayed again.
I'm just fairly new to coding and curious if this can be done, so I can improve the appearance of my code.
Edit: To solve the issue, I used str.split() to break up the indivudal fields in the rows of my CSV, so that they could be selected and held by a variable. The accepted answer shows the solution I used, but this is my final code in case this wasn't clear
with open ('details.csv', 'r') as stalking:
stalkingReader=csv.reader(stalking)
valid4=False
for column in stalkingReader:
if user in column[3]:
valid4=True
print("Here are the details for user {}... ".format(user))
splitter=row.split(',')
name=splitter[0]
age=splitter[1]
year=splitter[2]
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Year Group: {}".format(year))
postReport()
if valid4==False:
print("Sorry Fergus, this user doesn't seem to be in our records.")
with open("reportForFergusTwo.csv", "r") as highScore:
subject = []
difficulty = []
score = []
name = []
for line in highScore:
subject.append(line.split(',')[0])
difficulty.append(line.split(',')[1])
score.append(line.split(',')[2])
name.append(line.split(',')[3])
ind = score.index(max(score)
print("The highest score for this quiz is: ", max(score))
print("This was achieved by ", name[ind])
with opens (and will close) the .csv file.
Then, four empty lists are created.
Next, I loop through every line in the file, and I split every line using a comma as the delimiter. This produces a list of four elements, which are appended to each list.
You can use str.split() to break up the rows of your CSV so that you can individually reference the fields:
split_row = row.split(',')
score = split_row[2]
user = split_row[3]
print("The highest score for this quiz is: " + score)
print("This score was achieved by: " + user)
You can use csv library
import csv
with open("data", "r") as f:
reader = csv.reader(f)
# skip header
reader.next()
# organize data in 2D array
data = [ [ sub, dif, int(score), name ] for sub, dif, score, name in reader ]
# sort by score
data.sort(key=lambda x: x[2], reverse=True)
# pretty print
print "The highest score for this quiz is:", data[0][2]
print "This score was achieved by:", data[0][3]
(Posted solution on behalf of the OP).
To solve the issue, I used str.split() to break up the indivudal fields in the rows of my CSV, so that they could be selected and held by a variable. The accepted answer shows the solution I used, but this is my final code in case this wasn't clear
with open ('details.csv', 'r') as stalking:
stalkingReader=csv.reader(stalking)
valid4=False
for column in stalkingReader:
if user in column[3]:
valid4=True
print("Here are the details for user {}... ".format(user))
splitter=row.split(',')
name=splitter[0]
age=splitter[1]
year=splitter[2]
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Year Group: {}".format(year))
postReport()
if valid4==False:
print("Sorry Fergus, this user doesn't seem to be in our records.")

Python: leaderboard

I have been asked to design a leader board,
This is what I tried
def leader():
file = open ("res.txt","r")
reader = csv.reader(file)
print (("{:20s}{:20s}{:20s}{:20s}".format("\nPlayer","Matches played","Won","Lost")))
won = 100
for r in reader:
won = won-1
if r[2] == str(won):
print (("{:20s}{:20s}{:20s}{:20s}".format(r[0],r[1],r[2],r[3])))
file.close()
My csv file looks like this
Leeroy,19,7,12
Jenkins,19,8,11
Tyler,19,0,19
Napoleon Wilson,19,7,12
Big Boss,19,7,12
Game Dude,19,5,14
Macho Man,19,3,16
Space Pirate,19,6,13
Billy Casper,19,7,12
Otacon,19,7,12
Big Brother,19,7,12
Ingsoc,19,5,14
Ripley,19,5,14
M'lady,19,4,15
Einstein100,19,8,11
Dennis,19,5,14
Esports,19,8,11
RNGesus,19,7,12
Kes,19,9,10
Magnitude,19,6,13
I wish for it to display the person with the most wins first, can you help?
Try slurping the file into a list:
all_rows = list(reader)
Then sort all the rows on the key of most wins:
sorted_rows = sorted(all_rows, key=(lambda row: row[2]), reverse=True)
You might want to stack several sorts, or define a more complex key, so that you can enforce ordering within equal numbers of wins (for example, 7 wins of 8 plays is better than 7 wins of 100 plays).
keys = ["Player","Matches played","Won","Lost"]
# read file
with open("res.txt") as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line and
# split it by ',' then form a dictionary out of it
content = [dict(zip(keys,x.strip().split(','))) for x in content]
# sort the above list of dicts in decreasing orde.
final_result = sorted(content, key=lambda k: k['Won'], reverse=True)
print final_result# sorted By score
# first element is the one with highest Won value
print final_result[0] # highest Won

More complex sorting: How to cateorize data and sort the data within categories? (Python)

i have a question regarding a current program that I am trying to modify.
The current program I have:
def extract_names(filename):
names = []
f = open(filename, 'rU')
text = f.read()
yearmatch = re.search(r'Popularity\sin\s(\d\d\d\d)', text)
if not yearmatch:
sys.stderr.write('unavailable year\n')
sys.exit(1)
year = yearmatch.group(1)
names.append(year)
yeartuples = re.findall(r'<td>(\d+)</td><td>(\w+)</td>\<td>(\w+)</td>', text)#finds all patterns of date, boyname, and girlname, creates tuple)
rankednames = {}
for rank_tuple in yeartuples:
(rank, boyname, girlname) = rank_tuple
if boyname not in rankednames:
rankednames[boyname] = rank
if girlname not in rankednames:
rankednames[girlname] = rank
sorted_names = sorted(rankednames.keys(), key=lambda x: int(rankednames[x]), reverse = True)
for name in sorted_names:
names.append(name + " " + rankednames[name])
return names[:20]
#Boilerplate from this point**
def main():
args = sys.argv[1:]
if not args:
print 'usage: [--summaryfile] file [file ...]'
sys.exit(1)
summary = False
if args[0] == '--summaryfile':
summary = True
del args[0]
for filename in args:
names = extract_names(filename)
text = '\n'.join(names)
if summary:
outf = open(filename + '.summary', 'w')
outf.write(text + '\n')
outf.close()
else:
print text
if __name__ == '__main__':
main()
Takes information from a website regarding the most popular babynames of a certain year in a table, uses this data to create a list and print out a list of the babynames in order from the lowest rank (1000) to the highest rank (1). The modification I am trying to make is supposed to sort all of the names by alphabet (a first) but within each group of letters (group of all a's, group of all b's etc.) I am trying to sort the names by descending order within the letter groups, so the lowest ranked name that starts with an a would be the first name to show up. I have tried re.search for each letter but I dont think it works as intended that way. I am having the most trouble with the sorting within the letter categories. Are there any other approaches/solutions to this?
In the call to sorted, replace:
key=lambda x: int(rankednames[x]), reverse = True
with:
key=lambda x: (x[0], -int(rankednames[x]))
The general point is that you can always use a tuple to combine two or more different sort keys with one used first and the other as a "tie-breaker". The specific point is that we can easily simulate reverse=True because the key happens to be an integer and therefore can be negated: this trick wouldn't work for a string key.

Trouble printing the highest value read from a file

So I have created a quiz. I have saved the users quiz in a text file using python.
I have figured out how to allow a teacher to view the users names in alphabetical order with their score from the text file.
This is what my code looks like so far..
def alpha():
b = open("Class X.txt" , "r")
fo = b.readlines()
for x in sorted (fo):
print(x)
def beta():
b = open("Class Y.txt" , "r")
fo = b.readlines()
for x in sorted(fo):
print(x)
def charlie():
b = open("Class Z.txt" , "r")
fo = b.readlines()
for x in sorted(fo):
print(x)
option = input("Do you want to review the scores in/from: A)Alphabetical order with highest score.
if option == "A":
if Class == "X":
alpha()
elif Class == "Y":
beta()
elif Class == "Z":
charlie()`
What I have been trying to do is print all the users names in alphabetical order from a text file, which I have been successful with. However, I have been having great trouble in trying to print the highest score of each user along side their name instead of any of their scores.
My text file looks like this.
Joe:2
Jale:4
Laurence:1
Harry:2
Nakita:2
I was wondering whether anyone could help me figure out how to include just the highest score with the users name in alphabetical order like I have done, from the textfile which has been set out like how it it shown above.
I have also used the version Python 3.3.2.
from operator import itemgetter
lines = [line.strip().split(':') for line in open('results.txt')]
for each in lines:
each[1] = int(each[1])
lines.sort(key=itemgetter(1))
for each in lines:
print each[0],':',each[1]
Output:
Laurence : 1
Joe : 2
Harry : 2
Nakita : 2
Jale : 4
This print out the list of names sorted according to ascending order of the scores. If you want it alphabetically use (key=itemgetter(0))

Categories