Home > Net >  I am trying to calculate the average of student marks while reading from a txt file. but am having s
I am trying to calculate the average of student marks while reading from a txt file. but am having s

Time:03-07

I am very new to Programming and Here is my code so far while working in PyCharm..

f = open('studMarks.txt', 'r')
marks = 0
# Sort out names, split the words then sort which order
    for line in f:
    words = line.split()
    fname = words[0]
    lname = words[1]
    print(f"{lname},{fname}")
f.close()

f = open('studMarks.txt', 'r')
sum = 0
count = 0
for line in f:
    count  = 1
    sum  = float(line.split()[2])
    n = []
average = sum/count

print(f"{average}")

''' When using the for loop, it seems to display a value of 64.3 which I believe is for the total of the whole student list and average for all marks.

I need to produce the an output which displays the student names and average on the same line. I can do for the names but I cannot do it for the average.. as I keep getting errors. I don't know what to input in and sorry if this is a very dumb question..

CodePudding user response:

This is an interesting problem. From what I understand you have a text file that looks like this Johnny Ly 90 100 Adam Best 80 30 Tim Smith 10 20 in a file called studentMarks2.txt and want output like this Johnny_Ly 95.0 Adam_Best 55.0 Tim_Smith 15.0 if that is true then it can be done using code like this without pandas or csv though those would make this a lot easier.

fileContents = []

with open('studMarks2.txt','r') as f:
    fileContents = f.read().split()
    

students = dict()

names = []
for content in fileContents:
    if content.isnumeric():
        studentKey = '_'.join(names)
        currentScore = students.get(studentKey,[])        
        newScore = currentScore   [float(content)]
        students.update({studentKey:newScore})        
    else:
        if len(names) == 2:
            names.clear()
            names.append(content)
        else:
            names.append(content)
            
for student,scores in students.items():
    avg = sum(scores)/len(scores)
    print(student,avg,end=' ')

Broken down This part reads the contents and splits on white space

fileContents = []    
    with open('studMarks2.txt','r') as f:
        fileContents = f.read().split()

this part then iterates through the contents storing the names as keys in a dictionary and putting the scores in a list

students = dict()        
    names = []
    for content in fileContents:
        if content.isnumeric():
            studentKey = '_'.join(names)
            currentScore = students.get(studentKey,[])        
            newScore = currentScore   [float(content)]
            students.update({studentKey:newScore})        
        else:
            if len(names) == 2:
                names.clear()
                names.append(content)
            else:
                names.append(content)

Lastly it iterates over the dictionary and output the avg on one line

for student,scores in students.items():
    avg = sum(scores)/len(scores)
    print(student,avg,end=' ')

CodePudding user response:

great that you were getting into programming and a very good first stab at the above I would say. Can you clarify the problem a bit more. So for example, are you saying that your studMarks.txt file looks something like that

Johnny Ly 90 Adam Best 80 Tim Smith 10 Tim Smith 20 Adam Best 30 Johnny Ly 100

and you want output like this -

Johnny Ly 50 Adam Best 55 Tim Smith 15

So you want some kind of group by? If so, then the correct way to do this is using pandas which is better suited for this type of tabular data. You can also store your raw data in a csv file which is tidier.

Please confirm the above and I'll help you to get to the solution that you want.

  • Related