Back to Python: Making Decisions and Taking Control
So far, our little programs have had some interesting qualities: the ability to work with language, and the potential to save human effort through automation. A key feature of programming is the ability of machines to make decisions on our behalf, executing instructions when certain conditions are met, or repeatedly looping through text data until some condition is satisfied. This feature is known as control, and is the focus of this section.
Conditionals
Python supports a wide range of operators, such as < and >=, for testing the relationship between
values. The full set of these relational
operators are shown in Table 1-3.
Table 1-3. Numerical comparison operators
Operator | Relationship |
|---|---|
| Less than |
| Less than or equal to |
| Equal to (note this is two “ |
| Not equal to |
| Greater than |
| Greater than or equal to |
We can use these to select different words from a sentence of
news text. Here are some examples—notice only the operator is changed
from one line to the next. They all use sent7, the first sentence from text7 (Wall Street
Journal). As before, if you get an error saying that
sent7 is undefined, you need to
first type: from nltk.book import
*.
>>> sent7 ['Pierre', 'Vinken', ',', '61', 'years', 'old', ',', 'will', 'join', 'the', 'board', 'as', 'a', 'nonexecutive', 'director', 'Nov.', '29', '.'] >>> [w for w in sent7 if len(w) < 4] [',', '61', 'old', ',', 'the', 'as', 'a', '29', '.'] >>> [w for w in sent7 if len(w) <= 4] [',', ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access