I have used format in Python many times, but this one I am having trouble.
The solution should be simple, but I'm not getting it...
Here is the code:
test_list = df.groupby(['gender', 'admitted'])['student_id'].count()
print('The quantity of female students are {}.'.format(test_list[0] + test_list[1])
The output of test_list is:
gender admitted
female False 183
True 74
male False 125
True 118
Name: student_id, dtype: int64
So, test_list[0] is 183 and test_list[1] is 74.
The result expected from print is:
The quantity of female students are 257.
You forgot the closing ")" in your print statement. Because of that, the parser reached the end of the file before it expected to, thus raising an EOFError.
All you need to do is change it to this:
test_list = df.groupby(['gender', 'admitted'])['student_id'].count()
print('The quantity of female students are {}.'.format(test_list[0] + test_list[1]))
Related
I am new to python and trying to create a maths quiz program towards the end of the program I want to be able to print all the results in the file ( stored in the variable Reverseinfo) in numerical order. This doesn't seem to work , regardless of if I use the .sort function or the sorted() function. Any help would be appreciated, thanks
ReverseInfo already has scores and names put into the file
ReverseInfo= (score + (" ") + Name)
ClassANum=open("Class A Results High to Low.txt","a")
ClassANum.write(ReverseInfo)
ClassANum.write(" \n")
ClassANum.close()
ClassBNum=open("Class B Results High to Low.txt","a")
ClassBNum.write(ReverseInfo)
ClassBNum.write(" \n")
ClassBNum.close()
ClassCNum=open("Class C Results High to Low.txt","a")
ClassCNum.write(ReverseInfo)
ClassCNum.write(" \n")
ClassCNum.close()
if Viewscores=="Y":
Classresults=input("Which Class would you like to see the results of?")
if Classresults=="A":
ClassA=open("Class A Results.txt","r")
Class=ClassA
alphabet=ClassA.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="B":
ClassB=open("Class B Results.txt","r")
Class=ClassB
alphabet=ClassB.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="C":
ClassC=open("Class C Results.txt","r")
Class=ClassC
alphabet=ClassC.readlines()
for line in sorted(alphabet):
print(line)
else:
print ("That is not valid")
Numerical=input(" Do you want to see the results alphabetically?")
if Numerical=="Y":
NumClassresults=input("Which Class would you like to see the results of?")
if NumClassresults=="A":
ClassA=open("Class A Results High to Low.txt","r")
Class=ClassA
Hightolow=ClassA.readlines()
for line in sorted(Hightolow):
print(line)
elif NumClassresults=="B":
ClassA=open("Class B Results High to Low.txt","r")
Class=ClassB
Hightolow=ClassB.readlines()
for line in sorted(Hightolow):
print(line)
if NumClassresults=="C":
ClassA=open("Class C Results High to Low.txt","r")
Class=ClassC
Hightolow=ClassC.readlines()
for line in sorted(Hightolow):
print(line)
the data stored in Class A is: 10 Jamie
8 Jamie
8 Peter
10 Ham
4 Jack
10 Joseph
9 jamie
9 Yuan
9 Bob
10 John
6 Nash
8 John
10 josh
10 Honey
there is currently nothing stored in Class b file
finally in class c:
9 jamie
9 Yuan
9 Bob
8 Peter
8 Jamie
4 Jack
10 Joseph
10 John
10 Jamie
10 Ham
Try below (assuming your file looks like Name 100 with many rows)
with open("Class C Results High to Low.txt","r") as f:
lines = [(int(line.split(" ")[0]), line.split(" ")[1]) for line in f.readlines()]
for l in sorted(lines, key=lambda score_name: score_name[0]):
print l
Please let me know if there are any syntax errors (leave a comment), I couldn't test this - on the phone at the moment.
If the file is just lines with one integer per line, Hightolow will be a list of strings (that can be passed to int)
You need to pass a key function to sorted (or sort). In this case int does exactly what you need.
sorted(Hightolow, key=int)
ie use it in the loop like this:
for line in sorted(Hightolow, key=int):
Alternatively you can make Hightolow a list of ints as you read the file
Hightolow = [int(x) for x in ClassA]
I am trying to regex over an entire file, however I keep ending up with a list like this:
NONE
NONE
NONE
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>
How do I get the actual line back?
Here is my code:
dictionaryFile = "file.txt"
patternMatch = re.compile('^(\w{6,8})(\s+)(\d+)(\s+)(.+)(\s+)(\d{1,3}\s*-\s*\d{1,3})')
with open(dictionaryFile) as file:
for line in file:
result = patternMatch.search(line)
print result
Here is an example of the file I am regex'ing over:
HETELAVL 2 IS THERE A TELEPHONE ELSEWHERE ON 35 - 36
WHICH PEOPLE IN THIS HOUSEHOLD CAN
BE CONTACTED?
EDITED UNIVERSE: HETELHHD = 2
VALID ENTRIES
1 YES
2 NO
HEPHONEO 2 IS A TELEPHONE INTERVIEW ACCEPTABLE? 37 - 38
EDITED UNIVERSE: HETELHHD = 1 OR HETELAVL = 1
VALID ENTRIES
1 YES
2 NO
I would like to get this back:
HETELAVL 2 IS THERE A TELEPHONE ELSEWHERE ON 35 - 36
HEPHONEO 2 IS A TELEPHONE INTERVIEW ACCEPTABLE? 37 - 38
search() returns None if no position in the string matches the pattern.
Check if the result is not None and print line:
result = patternMatch.search(line)
if result is not None:
print line
search returns a match object so don't just print it as it will print the object use result.group(0) to get the actual line.
So in python class we are going over files and exceptions but the professor didn't explain it thoroughly hence why I'm lost to what exactly it is that he wants me to do, I would appreciate any help please. I understand that he wants us to copy the table 2 example but not quite sure. Here is the question.
The file ALW.txt contains the information shown in Table 1. Write a program to use the file to produce a text file containing the information in Table 2, in which the baseball teams list W-L percentage, as well as the total percentage.
Table 1:
ALW,W,L,W-L%
----------------
Oakland Athletics,96,66
----------------------
Texas Rangers,91,72
-------------------
Los Angeles,78,84
-------------------
Seattle Mariners,71,91
-----------------------
Houston Astros,51,111
---------------------------
Table 2:
-----
**Team.........................................W L W-L%**
-----
Oakland Athletics....................96 66 0.593
--------
Texas Rangers.........................91 72 0.558
------
Los Angeles.............................78 84 0.481
--------
Seattle Mariners.......................71 91 0.438
--------
Houston Astros.......................51 111 0.315
--------
Total:........................................387 423 0.484
so I came up with this code but I don't think I'm doing it right.
fob= open("C:/Users/Manny/Documents/Chapter 5 Assignments/ALW.txt","r")
fob.readline()
print ("Total number of teams: 5 ")
print ("Teams")
Oakland_Athletics_win = 96
Texas_Rangers_win = 91
Los_Angeles_win = 78
Seattle_Mariners_win = 71
Houston_Astros_win = 51
Oakland_Athletics_lose = 66
Texas_Rangers_lose = 72
Los_Angeles_lose = 84
Seattle_Mariners_lose = 91
Houston_Astros_lose = 111
total_win = Oakland_Athletics_win + Texas_Rangers_win + Los_Angeles_win + Seattle_Mariners_win + Houston_Astros_win
total_lose = Oakland_Athletics_lose + Texas_Rangers_lose + Los_Angeles_lose + Seattle_Mariners_lose + Houston_Astros_lose
win_lose_ratio = (Oakland_Athletics_lose + Oakland_Athletics_win)
win_lose_ratio2 = Oakland_Athletics_win / win_lose_ratio
total_ratio = total_win + total_lose
total_ratio2 = total_win / total_ratio
for line in fob:
x = line.split(",")
x2 = win_lose_ratio2
print ('\t','\t','\t','\t',"Wins",'\t',"Losses",'\t','\t',"Win-Lose%")
print (x[0],'\t',x[1],'\t',x[2],'\t','\t',(x2))
print ("Total: ",'\t','\t',total_win,'\t',total_lose,'\t',total_ratio2)
He basically wants you to convert how the statistics are displayed from one file and copy it to a different file in a different format.
I'd suggest that you first read the first file line by line and then split the line with commas. Then the elements at each index of the returned array can be formatted and written to an out file in the format he wants you to.
You teacher wants you to parse the file and produce a similar result than table 2 has.
You will need to:
open the file
Go through each line until you find the first Team
Add the strings separated by commas in that line to a list
Calculate the percentages
Carry on till the end
Write everything in anew file
It's a good exercise and Python is really good doing it
I am really stuck on this code that i've been working on and for 9 hours straight I cannot get it to work. Basically I am importing a file and splitting it to read the lines one by one and one of the tasks is to rearrange the lines in the file, for example the first line is: 34543, 2, g5000, Joseph James Collindale should look like : ['Collindale, Joseph James', '34543', g5000', '2']. So essentially it should loop over each line in the file and rearrange it to look like that format above. I created a function to check whether the length of the line is either 5 or 6 because they would both have a different format.
def tupleT(myLine):
myLine = myLine.split()
if len(myLine) == "5":
tuple1 = (myLine[4],myLine[3],myLine[0],myLine[2],myLine[1])
return tuple1
elif len(myLine) == "6":
tuple1 = (myLine[5],myLine[3]+ myLine[4],myLine[0],myLine[2], myLine[1])
return tuple1
mylist = []
x = input("Enter filename: ")
try :
f = open(x)
myLine = f.readline()
while (len(myLine)>0):
print(myLine[:-1])
myLine = f.readline()
tupleT(myLine)
f.close()
except IOError as e :
print("Problem opening file")
This is what the original file looks like in textpad and its called studs.txt:
12345 2 G400 Bart Simpson
12346 1 GH46 Lisa Simpson
12347 2 G401 Homer J Simpson
12348 4 H610 Hermione Grainger
12349 3 G400 Harry Potter
12350 1 G402 Herschel Shmoikel Krustofski
13123 3 G612 Wayne Rooney
13124 2 I100 Alex Ferguson
13125 3 GH4P Manuel Pellegrini
13126 2 G400A Mike T Sanderson
13127 1 G401 Amy Pond
13128 2 G402 Matt Smith
13129 2 G400 River Storm
13130 1 H610 Rose Tyler
Here is some commented code to get you started. Your code was a bit hard to read.
Consider renaming first, second and third since I have no idea what they are...
#!/usr/bin/env python
# this is more readable since there are actual names rather than array locations
def order_name(first, second, third, first_name, middle_name, last_name=None):
if not last_name:
# if there is no last name we got the last name in middle name (5 arguments)
last_name = middle_name
else:
# if there is a middle name add it to the first name to format as needed
first_name = "%s %s" % (first_name, middle_name)
return ("%s, %s" % (last_name, first_name), first, third, second)
with open('studs.txt') as o:
# this is a more standard way of iterating file rows
for line in o.readlines():
# strip line of \n
line = line.strip()
print "parsing " + line
# you can unpack a list to function arguments using the star operator.
print "ordered: " + str(order_name(*line.split()))
I have a string called new_file that I read from a file with these contents:
;ASP718I
;AspA2I
;AspBHI 0 6 9 15 ...
;AspCNI
;AsuI 37 116 272 348
...
I am using name = raw_input ("enter the enzyme ")
to get data from the user and I am trying to print the corresponding fields from the above file (new_file).
For the input ;AspBHI I'd like the program to print the corresponding line from the file:
;AspBHI 0 6 9 15 ...
How can I achieve this?
This is a start:
db = dict((x.split(" ")[0], x) for x in new_file.split("\n"))
name = raw_input("enter the enzyme ")
print db[name]
Also try to be nice next time, people might help you with more enthusiasm and even explain their approach.