Boss lesson · Unit 05
A log report
Parse lines into records, count them, rank them, report
What you practise
- Lines of text parsed into records, then counted, grouped and ranked into a report
Try a question from this lesson
Pick one
A server writes one line per event: a time, a level and a message. You want those three parts. What does this program show?
line = "09:15 ERROR disk full"
parts = line.split()
print(len(parts))Correct answer
4
Why
split() cuts at every space, and the message "disk full" has a space of its own. You get four pieces, not three. To keep the message whole, you have to tell split when to stop cutting.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
From a line to a record
split(" ", 2) cuts at a space at most 2 times, so the rest of the line stays in one piece.
Three pieces unpack into three names. Put them in a dictionary and you have a record: one event, with a label on every part.
Turning raw text into labelled data like this is called parsing.
line = "09:15 ERROR disk full"
time, level, msg = line.split(" ", 2)
rec = {"time": time, "level": level,
"msg": msg}
print(rec["msg"]) # disk fullConcept
Ranking the counts
items() gives the dictionary as pairs: ("ERROR", 5).
To rank them, sort the pairs with a key function that picks the count, the item at index 1 of each pair. reverse=True puts the biggest count first.
def by_count(pair):
return pair[1]
c = {"INFO": 3, "ERROR": 5, "WARN": 1}
ranked = sorted(c.items(), key=by_count,
reverse=True)
print(ranked[0]) # ('ERROR', 5)9 more exercises in the app
- 2× fill the blanks
- 3× type the answer
- 2× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.