SMS Sorter - 2
We use the list’s sort() function to sort the list. In Python, lists
are sorted as follows: if a list contains only strings, they are sorted into
alphabetical order; if a list contains only integers, they are sorted into
ascending order; if a list contains tuples or lists, the first item of the list
or tuple is used as the sorting key; if the list contains items of different
types, items of the same type are grouped together and each type is sorted
separately.
In this case, the sorting key depends on the user’s choice:
• The sort time() function uses the Inbox object’s time() function
to fetch the time when the message was received. The time
is returned in seconds since 1 January 1970, which is the standard
starting point for time measurements in many operating systems.
• The sort sender() function uses the sender’s phone number,
returned by the address() function, as the sorting key.
• The sort unread() function uses the function unread() which
returns 1 if the message is unread and 0 otherwise.
Since Python’s sort() function sorts integers into ascending order, we
have to make the timestamp and the unread flag negative,
-box.time(sms id) and -box.unread(sms id), as we prefer the
newest and the unread messages at the top of the list.
Each of these three functions prepares a list, msgs, that is ready to be
sorted in the desired way. The actual sorting and showing the resulting
list is the same in all the cases, so this task is separated into a function of
its own, show list().
After the msgs list has been sorted, we can drop off the sorting keys and
use only the second item in the tuple, the message content, to construct a
new list that includes message excerpts, as in the previous example. After
this, the sorted messages are ready to be displayed.
You could integrate Examples 15 and 16 to make a combined Inbox
searcher and sorter – a fully fledged personal messaging assistant. There is
one more related function, delete(), available in the Inbox object. It
works exactly like the functions content(), address() and time().
It is used to delete a message, so make sure you have backed up your
SMS inbox before trying it!
No comments:
Post a Comment