Calculation from text file - python

I have a text file containing:
SKT:SSG:2:1
NJW:UIA:1:0
SKT:TRP:3:2
SSG:NJW:0:2
I want to calculate the number of wins by each team corresponding to the number in the text file. Example:
SKT: 2
NJW: 2
UIA: 0
SSG: 0
Here's what i have so far:
fileName = input("Enter the file name:")
match = open(fileName)
table = []
for line in match:
contents = line.strip().split(':')
table.append(contents)
dictionary = {}
for line in table:
#how do i code the index of the team and it's score?
.
.
just a moment to test my understanding, if i were to calculate how many times each team wins, i have to ensure python is able to read that for example, SKT had a score of 2 against SSG of score 1 in game 1,which makes SKT the winner. Therefore, count + 1
however, I'm confused on how would i place the index of the team name corresponding to it's score. Any help is appreciated. Regards.

you can create a dict to store all the team winning score.
res = {}
for line in match:
team1,team2,score1,score2 = line.split(':')
if team1 not in res: res[team1] = 0
if team2 not in res: res[team2] = 0
if int(score1) == int(score2):
continue
else:
winner = team1 if int(score1) > int(score2) else team2
res[winner] += 1

You could use a dictionary.
fileName = input("Enter the file name:")
match = open(fileName)
d = {}
for line in match:
x, y, sx, sy = line.split(":")
if not x in d:
d[x] = 0
if not y in d:
d[y] = 0
if sx > sy:
d[x] += 1
elif sx < sy:
d[y] += 1
print(d)
Result:
{'SKT': 2, 'SSG': 0, 'NJW': 2, 'UIA': 0, 'TRP': 0}

Using collections.defaultdict simplifies the procedure:
import collections
scores = collections.defaultdict(int)
for line in table:
teamA,teamB,scoreA,scoreB = line.split(':')
# even if scores does not have the team key, += will create it
scores[teamA] += int(scoreA)
scores[teamB] += int(scoreB)

Related

Python - Trying to print each line that has a string value that matches the index provided

Now I'm still pretty new to python and programming in general, but I know I've gone a bit of a roundabout way this entire program. But here is what I have and what I want if anyone can help.
Begins by reading a text file e.g.
ADF101,Lecture,Monday,08:00,10:00,Jenolan,J10112,Joe Blo
ADF101,Tutorial,Thursday,10:00,11:00,Jenolan,J10115,Cat Blue
ALM204,Lecture,Monday,09:00,11:00,Tarana,T05201,Kim Toll
Then I make empty lists and append them with each index...
subjects = []
lecturer = []
for line in x:
f = line.split(',')
if len(fields) == 8:
subjects.append([0])
lecturer.append(f[7])
Then I provide an input that runs a function based on the input.
while True:
filter = input("Choose filter. Or [Q]uit: ")
if filter.upper() == 'S':
S(subjects)
break
elif filter.upper() == 'L':
L(lecturer)
break
Now if they choose L it runs this...
def L(lecturer):
print ("""
Lecturers
---------
""")
print (''.join(['[' + str(ind + 1) + '] ' + x for ind, x in enumerate(lecturer)]))
pick_lecturer = input("\npick a lecturer: ")
Which outputs like:
[1] Joe Blo
[2] Cat Blue
[3] Kim Toll
Here's where I'm stuck. I want to make it so that if the last
input is '1' it will read the file for each line with Joe Blo
and print the entire line. Without any external modules or libraries
Any guidance is appreciated. Thanks.
You can use csv module to read the file into a list. In this example, I read each row from the file into a namedtuple:
import csv
from collections import namedtuple
Item = namedtuple(
"Item", "subject type day time_from time_to some_column1 some_column2 name"
)
def L(data):
all_lecturers = list(set(d.name for d in data))
for i, name in enumerate(all_lecturers, 1):
print("[{}] {}".format(i, name))
while True:
try:
pick_lecturer = int(input("\npick a lecturer: "))
lecturer_name = all_lecturers[pick_lecturer - 1]
break
except:
continue
for d in [d for d in data if d.name == lecturer_name]:
print(d)
# 1. read the file
data = []
with open("your_file.txt", "r") as f_in:
reader = csv.reader(f_in)
for row in reader:
data.append(Item(*row))
# 2. choose a filter
while True:
filter_ = input("Choose filter. Or [Q]uit: ")
if filter_.upper() == "Q":
break
# if filter_.upper() == "S":
# S(data)
# break
elif filter_.upper() == "L":
L(data)
break
Prints:
Choose filter. Or [Q]uit: L
[1] Cat Blue
[2] Kim Toll
[3] Joe Blo
pick a lecturer: 3
Item(subject='ADF101', type='Lecture', day='Monday', time_from='08:00', time_to='10:00', some_column1='Jenolan', some_column2='J10112', name='Joe Blo')

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages

10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard#uct.ac.za Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
My Code:
fname = input("Enter file:")
fhandle = open(fname)
dic={}
for line in fhandle:
if not line.startswith("From "):
continue
else:
line=line.split()
line=line[5] # accesing the list using index and splitting it
line=line[0:2]
for bline in line:
dic[bline]=dic.get(bline,0)+1 # Using this line we created a dictionary having keys and values
#Now it's time to access the dictionary and sort in some way.
lst=[]
for k1,v1 in dic.items(): # dictionary er key value pair access korar jonno items method use kora hoyechhe
lst.append((k1,v1)) # dictionary er keys and corresponding values ke lst te append korlam
lst.sort() #lst take sort korlam. sorting is done through key
#print(lst)
for k1,v1 in lst: # we are able to access this list using key value pair as it was basically a dictionary before, It is just appended
print(k1,v1)
#print(dic)
#print(dic)
Desired Output:
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
My Output:
enter image description here
I don't understand what's going wrong.
Working Code. Break down the code in to simple form as much i can. So it will be easy to understand for you.
d = dict()
lst = list()
fname = input('enter the file name : ')
try:
fopen = open(fname,'r')
except:
print('wrong file name !!!')
for line in fopen:
stline = line.strip()
if stline.startswith('From:'):
continue
elif stline.startswith('From'):
spline = stline.split()
time = spline[5]
tsplit = time.split(':')
t1 = tsplit[0].split()
for t in t1:
if t not in d:
d[t] = 1
else:
d[t] = d[t] + 1
for k,v in d.items():
lst.append((k,v))
lst = sorted(lst)
for k,v in lst:
print(k,v)
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emailcount = dict()
for line in handle:
if not line.startswith("From "): continue
line = line.split()
line = line[1]
emailcount[line] = emailcount.get(line, 0) +1
bigcount = None
bigword = None
for word,count in emailcount.items():
if bigcount == None or count > bigcount:
bigcount = count
bigword = word
print(bigword, bigcount)
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = {}
for line in handle:
word = line.split()
if len(word) < 3 or word[0] != "From" : continue
full_hour = word[5]
hour = full_hour.split(":")
hour = str(hour[:1])
hour = hour[2:4]
if hour in counts :
counts[hour] = 1 + counts[hour]
else :
counts.update({hour:1})
lst = list()
for k, v in counts.items():
new_tup = (k, v)
lst.append(new_tup)
lst = sorted(lst)
for k, v in lst:
print(k,v)
counts=dict()
fill=open("mbox-short.txt")
for line in fill :
if line.startswith("From "):
x=line.split()
b=x[5]
y=b.split(":")
f=y[0]
counts[f]=counts.get(f,0)+1
l=list()
for k,v in counts.items():
l.append((k,v))
l.sort()
for k,v in l:
print(k,v)
I listen carefully in the online lessons, This is my code by what i learned in class. I think it will be easy for you to understand.
fn = input('Please enter file: ')
if len(fn) < 1: fn = 'mbox-short.txt'
hand = open(fn)
di = dict()
for line in hand:
ls = line.strip()
wds = line.split()
if 'From' in wds and len(wds) > 2:
hours = ls.split()
hour = hours[-2].split(':')
ch = hour[0]
di[ch] = di.get(ch, 0) + 1
tmp = list()
for h,t in di.items():
newt = (h,t)
tmp.append(newt)
tmp = sorted(tmp)
for h,t in tmp:
print(h,t)
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
line = line.strip()
if not line.startswith("From ") : continue
line = line.split()
hr = line[5].split(":")
hr = hr[0:1]
for piece in hr:
counts[piece] = counts.get(piece,0) + 1
lst = list()
for k,v in counts.items():
lst.append((k,v))
lst = sorted(lst)
for k,v in lst:
print(k,v)
fname = input("Enter file:")
fhandle = open(fname)
dic={}
for line in fhandle:
if not line.startswith('From '):
continue
else:
line=line.split()
line=line[5] # accesing the list using index and splitting it
line=line.split(':')
bline=line[0]
#for bline in line:
#print(bline)
dic[bline]=dic.get(bline,0)+1 # Using this line we created a
dictionary having keys and values
#Now it's time to access the dictionary and sort in some way.
lst=[]
for k1,v1 in dic.items(): # dictionary er key value pair access korar jonno items method use kora hoyechhe
lst.append((k1,v1)) # dictionary er keys and corresponding values ke lst te append korlam
lst.sort() #lst take sort korlam. sorting is done through key
#print(lst)
for k1,v1 in lst: # we are able to access this list using key value pair as it was basically a dictionary before, It is just appended
print(k1,v1)
#print(dic)
#print(dic)

Python making matching pairs

I've got the .txt file like this within:
Crista
Jame
7,3
2,0
Wiki
Rok
4,1
6,2
3,2
6,8
Pope
Lokk
5,2
0,1
3,1
Sam
Antony
4,3
9,1
My code to find all names and append them to the names[] list, and to find all digits and append them to the digits[] list (if there are more than two lines with digits in a row I didn't need them in the list before):
import re
f=open('mine.txt')
names=[]
digits=[]
count=0
for line in f:
line = line.rstrip()
if re.search('^[a-zA-Z]', line):
name=line
names.append(name)
if re.findall('^\d{1}:\d{1}', line):
if count < 2 :
digit=line
digits.append(digit)
count += 1
elif line != "" :
count = 0
Then I made pairs for matching names and digits:
my_pairs_dig=list()
while(digits):
a = digits.pop(0); b = digits.pop(0)
my_pairs_dig.append((a,b))
my_pairs_dig
my_pairs_names = list()
while(names):
a = names.pop(0); b = names.pop(0)
my_pairs_names.append((a,b))
my_pairs_names
outp=list(zip(my_pairs_names,my_pairs_dig))
And got this output:
[(('Crista', 'Jame'), ('7,3', '2,0')), (('Wiki', 'Rok'), ('4,1', '6,2')), (('Pope', 'Lokk'), ('5,2', '0,1')), (('Sam', 'Antony'),('4,3', '9,1'))]
But plans were changed and now my desired outout is:
[(('Crista', 'Jame'), ('7,3', '2,0')), (('Wiki', 'Rok'), ('4,1', '6,2'), ('3,2', '6,8')), (('Pope', 'Lokk'), ('5,2', '0,1'), ('3,1')), (('Sam', 'Antony'),('4,3', '9,1'))]
How can I rewrite my code to got the desired outoput?
Try this
with open('test.txt', 'r') as fp:
data = fp.read().split("\n")
i, res = 0, []
while i < len(data):
if data[i].isalpha():
names = (data[i], data[i+1])
i += 2
digits = []
while i < len(data) and not data[i].isalpha():
digits.append(data[i])
i += 1
digits = tuple(digits)
if len(digits) > 2:
res.append((names, digits[: 2], digits[2: ]))
else:
res.append((names, digits[: 2]))
print(res)
Output:
[(('Crista', 'Jame'), ('7,3', '2,0')), (('Wiki', 'Rok'), ('4,1', '6,2'), ('3,2', '6,8')), (('Pope', 'Lokk'), ('5,2', '0,1'), ('3,1',)), (('Sam', 'Antony'), ('4,3', '9,1'))]
Try this:
import re
digits=[]
result = []
name1, name2 = None, None
for line in f:
if line:
line = line.rstrip()
if re.search('^[a-zA-Z]', line):
if name1 and name2:
result.append(((name1, name2), *tuple(tuple(digits[i:i+2]) for i in range(0, len(digits), 2))))
name1, name2, digits = None, None, []
if name1:
name2 = line
else:
name1 = line
else:
digits.append(line)
if name1 and name2:
result.append(((name1, name2), *tuple(tuple(digits[i:i+2]) for i in range(0, len(digits), 2))))
name1, name2, digits = None, None, []
print(result)
Output:
[(('Crista', 'Jame'), ('7,3', '2,0')), (('Wiki', 'Rok'), ('4,1', '6,2'), ('3,2', '6,8')), (('Pope', 'Lokk'), ('5,2', '0,1'), ('3,1',)), (('Sam', 'Antony'), ('4,3', '9,1'))]
This is based on your assumption:
that's always two names and then 2,3 or 4 lines with numbers

How to use split() to separate and display a text file to calculate and average

I'm having trouble with the split() function. I have a module named printReport() that contains a name and 3 test scores in each line. I need to split the data so the names and scores can be displayed and have the average calculated. I'm positive I'm trying to do this completely wrong. I'm getting an IndexError: list index out of range. This is only the start of my problem. I still have no idea how to do the calculations and be displayed like below.
Student Name Score 1 Score 2 Score 3 Total
Dave 82 91 77 250
Tom 79 22 84 185
Dick 67 22 91 180
Mon Feb 8 15:12:08 2016
Can someone please explain what I'm doing wrong and how I would fix it.
### Subprogram detStudentData(fn, scores)
def getStudentData(fn, scores):
# Writes instructions for the user to follow
print("Enter the student names and scores following the prompts below.")
print("To finish entering student names, enter: ZZZ.\n")
# Set the flag for the loop
done = False
# Loop to get input from the usere
while done != True:
# Creates a newFile and enables append
newFile = open(fn, "a")
# Asks for a student name and assigns it to student_name
student_name = input("Please enter the student name (ZZZ to finish): ")
# Compairs student_name to see if it is equal to "ZZZ"
if student_name == "ZZZ":
# Sets the flag to True to exit the loop
done = True
# Asks for test scores if student_name is not equal "ZZZ"
else:
# Asks for test score 1 and assigns it to test_1
test_1 = input("Enter score 1: ")
# Asks for test score 2 and assigns it to test_2
test_2 = input("Enter score 2: ")
# Asks for test score 3 and assigns it to test_3
test_3 = input("Enter score 3: ")
print("\n")
newFile.write(student_name) # Writes student_name to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_1) # Writes test_1 to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_2) # Writes test_2e to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_3) # Writes test_3 to newFile
newFile.write("\n") # Wites a return to newFile
# Closes newFile
newFile.close()
# ==============================================================================
### Subprogram getTextFileContents(fn)
def getTextFileContents(fn):
# Opens the file and enables read
with open(fn, "r") as ins:
# Splits the text file before the ","
list = fn.split(",")
# Creates a loop to load the characters into a list
for line in ins:
# Appends the text to list
list.append(line)
# Returns the value in list
return list
# ==============================================================================
### Subprogram printReport(line)
def printReport(line):
# Prints the heading to show the test scores
print("__________________________________________________________")
print("Student Name Score 1 Score 2 Score 3 Total")
print("----------------------------------------------------------")
name = [] # Declare name a list
test1 = [] # Declare test1 a list
test2 = [] # Declare test2 a list
test3 = [] # Declare test a list
with open("grades.txt", "r") as f:
for line in f:
name.append(line.split(",", 1)[0])
line = name[0]
capacity = len(name)
index = 0
while index != capacity:
line = name[index]
for nameOut in line.split():
print(nameOut)
index = index + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test1.append(line.split(",", -1)[1])
line = test1[1]
capacity = len(test1)
index1 = 0
while index1 != capacity:
line = test1[index1]
for t1Out in line.split():
print(t1Out)
index1 = index1 + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test2.append(line.split(",", -1)[2])
line = test2[2]
capacity = len(test2)
index2 = 0
while index2 != capacity:
line = test2[index2]
for t2Out in line.split():
print(t2Out)
index2 = index2 + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test3.append(line.split(" ", -1)[3])
line = test3[3]
capacity = len(test3)
index3 = 0
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1
# ==============================================================================
def main():
fn = "grades.txt" # set the working file name
scores = 3 # set the number of scores
getStudentData(fn, scores) # Calls getStudentData()
line = getTextFileContents(fn) # Assigns getTextFileContent() to line
printReport(line) # Calls printReport()
main()
Check the lines
line = test1[1]
line = test2[2]
line = test3[3]
You should start the list from 0, not 1, 2, 3
The offending section is this:
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1
The first line should be:
while index3 != capacity:
Note that manually incrementing an index is probably not the best way to loop over a list in Python. A more pythonic way might be something like:
for item in test3:
for t3out in item.split():
print(t3out)
Also, if you're going to stick with incrementing manually, you need to remove the index = index + 1 from inside the for loop. You should only increment after processing each line.
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1

Sorting error for average score

viewclass= input("choose a class number and either alphabetically, average or highest?")#type in what you want to select
if viewclass=='1 average':#variable inputted
with open("1.txt") as f:#open text file
d = {}
for line in f:
column = line.split(":")#split name and score
names = column[0]#names in column
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)#name and scores added to end of list
count = count + 1
for names, v in sorted(d.items()):#sorted
average = (sum(v)/len(v))
print(names,average)#average score printed
averages=[]
averages.append(average)
elif viewclass=='2 average':
with open("2.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
for names, v in sorted(d.items()):
average = (sum(v)/len(v))
print(names,average)
averages=[]
averages.append(average)
elif viewclass=='3 average':
with open("3.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
for names, v in sorted(d.items()):
average = (sum(v)/len(v))
print(names,average)
averages=[]
averages.append(average)
my other code works but when for this when I run it signal file it works but when I select it I get this error
choose a class number and either alphabetically, average or highest?1 average
Traceback (most recent call last):
File "C:/Users//Documents/New folder (2)/14343 - Copy.py", line 10, in <module>
for line in f:
ValueError: I/O operation on closed file.
with open("3.txt") as f:
d = {}
You are finishing the with function by creating the dictionary
When with is finished the file opened are closed
It should be like the following
with open("2.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
with is know as context manager they open the file when the function starts and closes the file when their function finishes
You have done the same error many times
The actual error is suggesting that you are reading content of a closed file object

Categories

Resources