Chelsea Lewis
Chelsea Lewis

Reputation: 257

How to find which line in a text file has the most names in it

I have the attendance for numerous days listed on separate lines of a text file, the day of the week followed by a comma and then the names of those who attended printed separated by commas, eg Monday, Jane, John, Joe, Mary.

I need to find and print the day with the most students and that number of students that attended.

file = open('attendace.txt', 'r')
for line in file:

    print(' '', had the highest attendance with, '', students')
file.close() 

Upvotes: 0

Views: 31

Answers (1)

ababuji
ababuji

Reputation: 1731

Assuming that you .txt file has attendance details like this

Monday, Jane, John, Joe, Mary
Tuesday, Jane, John, Joe, Mary
Wednesday, Jane, John, Joe, Mary, Dave1, Dave2
Thursday, Jane, John
Friday, Jane, John, Joe, Mary, Dave
Saturday, Jane
Sunday, Jane, John, Joe, Mary, Dave
Monday, Jane, John, Joe

Then, we open the file, append each line as a string to a list called attendanceList.

attendanceList = []
file = open('/Users/abhi/Desktop/attendance.txt', 'r') #Enter your file path here
for line in file:
    attendanceList.append([line])

We then go inside the list of list of strings, and split it on comma, so I can get back another list which properly comma separated (this step can be done above itself, but I'm separating it on purpose.

newList = []

for i in attendanceList:
    for j in i:
        new = j.split(",")
        newList.append(new)

print(newList)

Now you will have the lists in the form, [[day1, name1,name2, ..], [day2,name1, name2, name3, ..]

The line below simply picks out the list inside the list with the max length

maxStudents = max(newList, key = len)
print("\n")
print(maxStudents)

Since the first element inside the maximum element list will always represent the day

day = maxStudents[0]

The number of students, will be equal to the length of the maxStudents list - 1, since the first element represents the day

numStudents = len(maxStudents) - 1


print(("{} had the maximum attendance with, {} students").format(day, numStudents))
file.close()

Upvotes: 1

Related Questions