Thy Thy - 6 months ago 12
jQuery Question

How to parse csv file and compute stats based on that data

I have a task which requires me to make a program in python that reads a text file which has information about people (name, weight and height).

Then I need the program to ask for the user to enter a name then look for that name in the text file and print out the line which includes that name and the person's height and weight.

Then the program has to work out the average weight of the people and average height.

The text file is:

James,73,1.82,M
Peter,78,1.80,M
Jay,90,1.90,M
Beth,65,1.53.F
Mags,66,1.50,F
Joy,62,1.34,F


So far I have this code which prints out the line using the name that has been typed by the user but I don't know to assign the heights and the weights:

search = input("Who's information would you like to find?")
with open("HeightAndWeight.txt", "r") as f:
for line in f:
if search in line:
print(line)

Answer

Use:

splitted_line = line.split(',', 4)

to split the line you just found into four parts, using the comma , as a delimiter. You then can get the first part (the name) with splitted_line[0], the second part (age) with splitted_line[1] and so on. So, to print out the persons name, height and weight:

print('The person %s is %s years old and %s meters tall.' % (splitted_line[0], splitted_line[1], splitted_line[2]))

To get the average on height and age, you need to know how many entries are in your file, and then just add up age and height and divide it by the number of entries/persons. The whole thing would look like:

search = input("Who's information would you like to find?")
total = 0
age = 0
height = 0
with open("HeightAndWeight.txt", "r") as f:
for line in f:
    total += 1
    splitted_line = line.split(',', 4)
    age += int(splitted_line[1])
    height += int(splitted_line[2]) 
    if search in line:
        print('The person %s is %s years old and %s meters tall.' % (splitted_line[0], splitted_line[1], splitted_line[2]))
average_age = age / total
average_height = height / total

That's one straightforward way to do it, and hopefully easy to understand as well.

Comments