简体   繁体   中英

How can I create an average from a text file in Python 3.5.2?

I've been struggling with this for two days now and I can't seem to find any help. I need to search the file for a student ID (1001 is my test ID being used) and then add the numbers in each line that takes place below each occurrence of the student ID together in order to get an average.

filename = input("Enter file name: \n"
                 "Example: Grade Data.txt \n")
myFile = open(filename, "r")    
selectSID = input("Enter SID: \n")
gradesNum = myFile.read().count(selectSID)
grades = myFile.read()
gradetotal = sum()
average = (gradetotal/gradesNum)
print(average)

The text file that is being opened looks like this:

1001
95
1002
99
1001
96
1002
0
1001
84
1002
25
1001
65
1002
19

This looks like homework so I don't want to write the code for you but here is a pseudo code (there are multiple ways to achieve what you want, this is just a simple beginner level code):

Open file to read
get two lines from the file
    is the line1 interesting to me?
        yes -> store value from line2 in an array
        no -> ignore line2
close file

get average

Some useful references:

from collections import defaultdict
# with open('filename') as f:
#     file = [for i in f]
# in this case, it's the list below
file = [1001,95,1002,99,1001,96,1002,0,1001,84,1002,25,1001,65,1002,19]
infos = defaultdict(list)
sids = file[::2]    # select sid info
grades = file[1::2] # select grade info 

for sid,grade in zip(sids,grades):
    infos[sid].append(grade)

print(infos[1001])
print(infos[1002])

out:

[95, 96, 84, 65]
[99, 0, 25, 19]

in this point, you can sum, average, max or min whatever you want.

Please don't use this code for your homework (use @Aditya's method); you need to learn the basics before using fancy libraries. However, I just learned about collections.defaultdict and I wanted to use it. Watch this video for a great demo on defaultdict .

import collections
import statistics

# This little guy will hold all of our grades
# https://youtu.be/lyDLAutA88s is a great video using it
grades = collections.defaultdict(list)

def get_next_num(file):
    """get the next line of a file,
    remove any whitespace surrounding it,
    and turn it into an integer"""
    return int(next(file).strip())

with open('tmp.txt') as myfile:
    while True:
        try:
            # seriously, watch the video
            grades[get_next_num(myfile)].append(get_next_num(myfile))
        except StopIteration: # end of file
            break
student_id = int(input('Enter student ID. Choices: {} : '.format(list(grades.keys()))))
print(statistics.mean(grades[student_id]))

Updated Answer:

Okay, so I think I understand your question now... Same thing, except I suggest using a list, and as long as the file stays in the same format (SID, Score, so on...), this should work, and requires minimal understanding of Python (ie No weird libraries like glob ):

filename = input("Enter file name: \n"
             "Example: Grade Data.txt \n")
myFile = open(filename, "r")    
selectSID = input("Enter SID: \n")
raw = myFile.read()   ## Raw contents of file.
val = raw.count( selectSID )  ## Returns number of occurences
print( "Occurrences: ", val )  ## Or do something else...

lines = raw.split("\n")   ## Create a list containing each new line
scores = []   ## A list that will contain all your scores
while selectSID in lines:
    val = lines.index( selectSID )   ## Returns where it is in the list,
    score = lines[ val+1 ]   ## Gets the item at that position (index) Because the score is one line after the SID
    scores.append( int(score) ) ## Adds the score to the list. --Suggest you look into how to safely capturing "int"s (try, except, etc) so the program doesn't crash if the score isn't a number (Advance)
    lines.remove( selectSID )   ## automatically removes first occurrence of the SID (cause that's the one we just used)
avg = sum(scores) / len(scores)  ## sum() function is self explanatory (takes a list or tuple [a sequence] and adds all values (must be all numbers), THEN len() is just length. 

This will return an integer, or with your file, will print:

Occurrences: 4


Regardless if this answered your question, my tip for learning basics is understanding file types and what they can do. In your case, you will mainly need to focus on strings (text) and integers (whole numbers). Using Pythons IDLE, declare a variable, and type the name and a dot, and use tab to scroll through each functions available. Example:

>>> myString = "Hello World"
>>> myString.[TAB]  #--> [Context Menu Here]

Once you pick one form the list, enter an opening parenthesis "(", and it will give a brief description of what it does.



Hope that helps, and sorry for the lengthy reply (I was trying to explain and give pointers (tips) since you said you were a noob)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM