Text
stringlengths
1
9.41k
Assuming that we have defined the variables last, first, and number, we could write a dictionary assignment statement as follows: directory[last,first] = number The expression in brackets is a tuple.
We could use tuple assignment in a for loop to traverse this dictionary. **for last, first in directory:** print(first, last, directory[last,first]) This loop traverses the keys in directory, which are tuples.
It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number. ##### 10.8 Sequences: strings, lists, and tuples - Oh My! I have focused on lists of tuples, but almost all of the examples in this chapter also work with lists of lists, tuples of tuples, and tuples of l...
To avoid enumerating the possible combinations, it is sometimes easier to talk about sequences of sequences. In many contexts, the different kinds of sequences (strings, lists, and tuples) can be used interchangeably.
So how and why do you choose one over the others? To start with the obvious, strings are more limited than other sequences because the elements have to be characters. They are also immutable.
If you need the ability to change the characters in a string (as opposed to creating a new string), you might want to use a list of characters instead. Lists are more common than tuples, mostly because they are mutable.
But there are a few cases where you might prefer tuples: ----- 1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list.
In other contexts, you might prefer a list. 2. If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string. 3.
If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing. Because tuples are immutable, they don’t provide methods like sort and reverse, which modify existing lists.
However Python provides the built-in functions sorted and reversed, which take any sequence as a parameter and return a new sequence with the same elements in a different order. ##### 10.9 Debugging Lists, dictionaries and tuples are known generically as data structures; in this chapter we are starting to see compoun...
Compound data structures are useful, but they are prone to what I call shape errors; that is, errors caused when a data structure has the wrong type, size, or composition, or perhaps you write some code and forget the shape of your data and introduce an error. For example, if you are expecting a list with one integer ...
Often** if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to spend some time to build scaffolding. **ruminating Take some time to think!
What kind of error is it: syntax, runtime,** semantic? What information can you get from the error messages, or from the output of the program? What kind of error could cause the problem you’re seeing?
What did you change last, before the problem appeared? **retreating At some point, the best thing to do is back off, undoing recent changes,** until you get back to a program that works and that you understand.
Then you can start rebuilding. Beginning programmers sometimes get stuck on one of these activities and forget the others.
Each activity comes with its own failure mode. For example, reading your code might help if the problem is a typographical error, but not if the problem is a conceptual misunderstanding.
If you don’t understand ----- what your program does, you can read it 100 times and never see the error, because the error is in your head. Running experiments can help, especially if you run small, simple tests.
But if you run experiments without thinking or reading your code, you might fall into a pattern I call “random walk programming”, which is the process of making random changes until the program does the right thing.
Needless to say, random walk programming can take a long time. You have to take time to think. Debugging is like an experimental science.
You should have at least one hypothesis about what the problem is.
If there are two or more possibilities, try to think of a test that would eliminate one of them. Taking a break helps with the thinking. So does talking.
If you explain the problem to someone else (or even to yourself), you will sometimes find the answer before you finish asking the question. But even the best debugging techniques will fail if there are too many errors, or if the code you are trying to fix is too big and complicated.
Sometimes the best option is to retreat, simplifying the program until you get to something that works and that you understand. Beginning programmers are often reluctant to retreat because they can’t stand to delete a line of code (even if it’s wrong).
If it makes you feel better, copy your program into another file before you start stripping it down.
Then you can paste the pieces back in a little bit at a time. Finding a hard bug requires reading, running, ruminating, and sometimes retreating.
If you get stuck on one of these activities, try the others. ##### 10.10 Glossary **comparable A type where one value can be checked to see if it is greater than,** less than, or equal to another value of the same type.
Types which are comparable can be put in a list and sorted. **data structure A collection of related values, often organized in lists, dictionaries,** tuples, etc. **DSU Abbreviation of “decorate-sort-undecorate”, a pattern that involves building** a list of tuples, sorting, and extracting part of the result. **gath...
Immutable types like integers, floats,** and strings are hashable; mutable types like lists and dictionaries are not. ----- **scatter The operation of treating a sequence as a list of arguments.** **shape (of a data structure) A summary of the type, size, and composition of** a data structure. **singleton A list (...
The right side is evaluated and then its elements are assigned to the variables on the left. ##### 10.11 Exercises **Exercise 1: Revise a previous program as follows: Read and parse the “From”** lines and pull out the addresses from the line.
Count the number of messages from each person using a dictionary. After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary.
Then sort the list in reverse order and print out the person who has the most commits. Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Enter a file name: mbox-short.txt cwen@iupui.edu 5 Enter a file name: mbox.txt zqian@umich.edu 195 **Exercise 2: This program counts the distribution of the hou...
You can pull the hour from the “From” line by finding the time string and then splitting that string into parts using the colon character.
Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below. Sample Execution: python timeofday.py Enter a file name: mbox-short.txt 04 3 06 1 07 1 09 2 ----- 10 3 11 6 14 1 15 2 16 4 17 2 18 1 19 1 **Exercise 3: Write a program that reads a file and print...
Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z.
Find text samples from several different languages and see how letter frequency varies between languages.
Compare your results with the tables at wikipedia.org/wiki/Letter_frequencies. ----- ## Chapter 11 # Regular expressions So far we have been reading through files, looking for patterns and extracting various bits of lines that we find interesting.
We have been using string methods like split and find and using lists and string slicing to extract portions of the lines. This task of searching and extracting is so common that Python has a very powerful library called regular expressions that handles many of these tasks quite elegantly. The reason we have not intr...
As a matter of fact, entire books have been written on the topic of regular expressions. In this chapter, we will only cover the basics of regular expressions.
For more detail on regular expressions, see: [http://en.wikipedia.org/wiki/Regular_expression](http://en.wikipedia.org/wiki/Regular_expression) [https://docs.python.org/2/library/re.html](https://docs.python.org/2/library/re.html) The regular expression library re must be imported into your program before you can us...
The simplest use of the regular expression library is the search() function.
The following program demonstrates a trivial use of the search function. _# Search for lines that contain 'From'_ import re hand = open('mbox-short.txt') **for line in hand:** line = line.rstrip() **if re.search('From:', line):** print(line) _# Code: http://www.pythonlearn.com/code3/re01.py_ We open the file, loop ...
This program does not ----- use the real power of regular expressions, since we could have just as easily used line.find() to accomplish the same result. The power of the regular expressions comes when we add special characters to the search string that allow us to more precisely control which lines match the strin...
Adding these special characters to our regular expression allow us to do sophisticated matching and extraction while writing very little code. For example, the caret character is used in regular expressions to match “the beginning” of a line.
We could change our program to only match lines where “From:” was at the beginning of the line as follows: _# Search for lines that start with 'From'_ import re hand = open('mbox-short.txt') **for line in hand:** line = line.rstrip() **if re.search('^From:', line):** print(line) _# Code: http://www.pythonlearn.com/c...
This is still a very simple example that we could have done equivalently with the startswith() method from the string library.
But it serves to introduce the notion that regular expressions contain special action characters that give us more control as to what will match the regular expression. ##### 11.1 Character matching in regular expressions There are a number of other special characters that let us build even more powerful regular expr...
The most commonly used special character is the period or full stop, which matches any character. In the following example, the regular expression “F..m:” would match any of the strings “From:”, “Fxxm:”, “F12m:”, or “F!@m:” since the period characters in the regular expression match any character. _# Search for lines...
These special characters mean that instead of matching a single character in the search string, they match zero-or-more characters (in the case of the asterisk) or one-or-more of the characters (in the case of the plus sign). We can further narrow down the lines that we match using a repeated wild card character in th...
So this will match the following line: _From: uct.ac.za_ You can think of the “.+” wildcard as expanding to match all the characters between the colon character and the at-sign. _From:_ It is good to think of the plus and asterisk characters as “pushy”.
For example, the following string would match the last at-sign in the string as the “.+” pushes outwards, as shown below: _From: iupui.edu_ It is possible to tell an asterisk or plus sign not to be so “greedy” by adding another character.
See the detailed documentation for information on turning off the greedy behavior. ##### 11.2 Extracting data using regular expressions If we want to extract data from a string in Python we can use the findall() method to extract all of the substrings which match a regular expression.
Let’s use the example of wanting to extract anything that looks like an email address from any line regardless of format.
For example, we want to pull the email addresses from each of the following lines: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: <postmaster@collab.sakaiproject.org> for <source@collab.sakaiproject.org>; Received: (from apache@localhost) Author: stephen.marquard@uct.ac.za ----- We don’t want ...
This following program uses findall() to find the lines with email addresses in them and extract one or more addresses from each of those lines. import re s = 'A message from csev@umich.edu to cwen@iupui.edu about meeting @2PM' lst = re.findall('\S+@\S+', s) print(lst) _# Code: http://www.pythonlearn.com/code3/re05.p...
We are using a two-character sequence that matches a non-whitespace character (\\S). The output of the program would be: ['csev@umich.edu', 'cwen@iupui.edu'] Translating the regular expression, we are looking for substrings that have at least one non-whitespace character, followed by an at-sign, followed by at least...
The “\\S+” matches as many non-whitespace characters as possible. The regular expression would match twice (csev@umich.edu and cwen@iupui.edu), but it would not match the string “@2PM” because there are no non-blank characters before the at-sign.
We can use this regular expression in a program to read all the lines in a file and print out anything that looks like an email address as follows: _# Search for lines that have an at sign between characters_ import re hand = open('mbox-short.txt') **for line in hand:** line = line.rstrip() x = re.findall('\S+@\S+', l...
Since findall() returns a list, we simply check if the number of elements in our returned list is more than zero to print only lines where we found at least one substring that looks like an email address. If we run the program on mbox.txt we get the following output: ['wagnermr@iupui.edu'] ['cwen@iupui.edu'] -----...
Let’s declare that we are only interested in the portion of the string that starts and ends with a letter or a number. To do this, we use another feature of regular expressions.
Square brackets are used to indicate a set of multiple acceptable characters we are willing to consider matching. In a sense, the “\\S” is asking to match the set of “non-whitespace characters”.
Now we will be a little more explicit in terms of the characters we will match. Here is our new regular expression: [a-zA-Z0-9]\S*@\S*[a-zA-Z] This is getting a little complicated and you can begin to see why regular expressions are their own little language unto themselves.
Translating this regular expression, we are looking for substrings that start with a single lowercase letter, uppercase letter, or number “[a-zA-Z0-9]”, followed by zero or more non-blank characters (“\\S*”), followed by an at-sign, followed by zero or more non-blank characters (“\\S*”), followed by an uppercase or low...
Note that we switched from “+” to “*” to indicate zero or more non-blank characters since “[a-zA-Z0-9]” is already one non-blank character.
Remember that the “*” or “+” applies to the single character immediately to the left of the plus or asterisk. If we use this expression in our program, our data is much cleaner: _# Search for lines that have an at sign between characters_ _# The characters must be a letter or number_ import re hand = open('mbox-short...
This is because when we append “[a-zA-Z]” to the end of our regular expression, we are demanding that whatever string the regular expression parser finds must end with a letter.
So when it sees the “>” after “sakaiproject.org>;” it simply stops at the last “matching” letter it found (i.e., the “g” was the last good match). Also note that the output of the program is a Python list that has a string as the single element in the list. ##### 11.3 Combining searching and extracting If we want to...
We only want to extract numbers from lines that have the above syntax. We can construct the following regular expression to select the lines: ^X-.*: [0-9.]+ Translating this, we are saying, we want lines that start with “X-”, followed by zero or more characters (“.*”), followed by a colon (“:”) and then a space.
After the space we are looking for one or more characters that are either a digit (0-9) or a period “[0-9.]+”.
Note that inside the square brackets, the period matches an actual period (i.e., it is not a wildcard between the square brackets). This is a very tight expression that will pretty much match only the lines we are interested in as follows: _# Search for lines that start with 'X' followed by any non_ _# whitespace cha...
While it would be simple enough to use split, we can use another feature of regular expressions to both search and parse the line at the same time. Parentheses are another special character in regular expressions.
When you add parentheses to a regular expression, they are ignored when matching the string. But when you are using findall(), parentheses indicate that while you want the whole expression to match, you only are interested in extracting a portion of the substring that matches the regular expression. So we make the fol...
The number can include a decimal._ _# Then print the number if it is greater than zero._ import re hand = open('mbox-short.txt') **for line in hand:** line = line.rstrip() x = re.findall('^X\S*: ([0-9.]+)', line) **if len(x) > 0:** print(x) _# Code: http://www.pythonlearn.com/code3/re11.py_ Instead of calling search...
We want to find lines that match the entire expression but we only want to extract the integer number at the end of the line, so we surround “[0-9]+” with parentheses. When we run the program, we get the following output: ['39772'] ['39771'] ['39770'] ['39769'] ... Remember that the “[0-9]+” is “greedy” and it tr...
This “greedy” behavior is why we get all five digits for each number.
The regular expression library expands in both directions until it encounters a non-digit, or the beginning or the end of a line. Now we can use regular expressions to redo an exercise from earlier in the book where we were interested in the time of day of each mail message.
We looked for lines of the form: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 and wanted to extract the hour of the day for each line. Previously we did this with two calls to split.
First the line was split into words and then we pulled out the fifth word and split it again on the colon character to pull out the two characters we were interested in. ----- While this worked, it actually results in pretty brittle code that is assuming the lines are nicely formatted.
If you were to add enough error checking (or a big try/except block) to insure that your program never failed when presented with incorrectly formatted lines, the code would balloon to 10-15 lines of code that was pretty hard to read. We can do this in a far simpler way with the following regular expression: ^From .*...
This is the definition of the kinds of lines we are looking for. In order to pull out only the hour using findall(), we add parentheses around the two digits as follows: ^From .* ([0-9][0-9]): This results in the following program: _# Search for lines that start with From and a character_ _# followed by a two digit...
For example, we can find money amounts with the following regular expression. ----- import re x = 'We just received $10.00 for cookies.' y = re.findall('\$[0-9.]+',x) Since we prefix the dollar sign with a backslash, it actually matches the dollar sign in the input string instead of matching the “end of line”, and ...
Note: Inside square brackets, characters are not “special”. So when we say “[0-9.]”, it really means digits or a period.
Outside of square brackets, a period is the “wildcard” character and matches any character.
Inside square brackets, the period is a period. ##### 11.5 Summary While this only scratched the surface of regular expressions, we have learned a bit about the language of regular expressions.
They are search strings with special characters in them that communicate your wishes to the regular expression system as to what defines “matching” and what is extracted from the matched strings. Here are some of those special characters and character sequences: ˆ Matches the beginning of the line. $ Matches the end ...
Matches any character (a wildcard). \\s Matches a whitespace character. \\S Matches a non-whitespace character (opposite of \\s). - Applies to the immediately preceding character and indicates to match zero or more of the preceding character(s). *?
Applies to the immediately preceding character and indicates to match zero or more of the preceding character(s) in “non-greedy mode”. - Applies to the immediately preceding character and indicates to match one or more of the preceding character(s). +?
Applies to the immediately preceding character and indicates to match one or more of the preceding character(s) in “non-greedy mode”. [aeiou] Matches a single character as long as that character is in the specified set. In this example, it would match “a”, “e”, “i”, “o”, or “u”, but no other characters. [a-z0-9] You ...
This example is a single character that must be a lowercase letter or a digit. [ˆA-Za-z] When the first character in the set notation is a caret, it inverts the logic. This example matches a single character that is anything other than an uppercase or lowercase letter. ( ) When parentheses are added to a regular expr...
So if you have a Macintosh or Linux system, you can try the following commands in your command-line window. $ grep '^From:' mbox-short.txt From: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: zqian@umich.edu From: rjlowe@iupui.edu This tells grep to show you lines that start with the string “From:” i...
If you experiment with the grep command a bit and read the documentation for grep, you will find some subtle differences between the regular expression support in Python and the regular expression support in grep.
As an example, grep does not support the non-blank character “\\S” so you will need to use the slightly more complex set notation “[ˆ ]”, which simply means match a character that is anything other than a space. ##### 11.7 Debugging Python has some simple and rudimentary built-in documentation that can be quite helpf...
This documentation can be viewed in the Python interpreter in interactive mode. You can bring up an interactive help system using help(). >>> help() help> modules If you know what module you want to use, you can use the dir() command to find the methods in the module as follows: ----- >>> import re >>> dir(re) ...
'compile', 'copy_reg', 'error', 'escape', 'findall', _'finditer', 'match', 'purge', 'search', 'split', 'sre_compile',_ _'sre_parse', 'sub', 'subn', 'sys', 'template']_ You can also get a small amount of documentation on a particular method using the dir command. >>> help (re.search) Help on function search in module ...
We call this “brittle code” because it is easily broken. **greedy matching The notion that the “+” and “*” characters in a regular ex-** pression expand outward to match the largest possible string. **grep A command available in most Unix systems that searches through text files** looking for lines that match regular...
The command name stands for “Generalized Regular Expression Parser”. **regular expression A language for expressing more complex search strings.
A** regular expression may contain special characters that indicate that a search only matches at the beginning or end of a line or many other similar capabilities. **wild card A special character that matches any character.
In regular expressions** the wild-card character is the period. ----- ##### 11.9 Exercises **Exercise 1: Write a simple program to simulate the operation of the grep com-** mand on Unix.
Ask the user to enter a regular expression and count the number of lines that matched the regular expression: $ python grep.py Enter a regular expression: ^Author mbox.txt had 1798 lines that matched ^Author $ python grep.py Enter a regular expression: ^Xmbox.txt had 14368 lines that matched ^X $ python grep.py Enter...
Compute the average of the numbers and print out the average. Enter file:mbox.txt 38549.7949721 Enter file:mbox-short.txt 39756.9259259 ----- ----- ## Chapter 12 # Networked programs While many of the examples in this book have focused on reading files and looking for data in those files, there are many differe...
Then we will read through the web page data and parse it. ##### 12.1 HyperText Transport Protocol - HTTP The network protocol that powers the web is actually quite simple and there is builtin support in Python called sockets which makes it very easy to make network connections and retrieve data over those sockets in ...