9.10. Parsing lines¶
Usually when we are reading a file we want to do something to the lines other than just printing the whole line. Often we want to find the “interesting lines” and then parse the line to find some interesting part of the line. What if we wanted to print out the day of the week from those lines that start with “From “?
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
The split
method is very effective when faced with this
kind of problem. We can write a small program that looks for lines where
the line starts with “From “, split
those lines, and then
print out the third word in the line:
Later, we will learn increasingly sophisticated techniques for picking the lines to work on and how we pull those lines apart to find the exact bit of information we are looking for.
The following code should open a file and read through the lines, splitting them when a line starts with “Hello”, then printing the second word in the line. Watch out for extra pieces of code and indentation.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.