Text stringlengths 1 9.41k |
|---|
You can also put comments in. |
Here
is an example:
pattern = r"""(?x)[AB]\d+ # Match A or B followed by some digits
[CD]\d+ # Match C or D followed by some digits
"""
**print(re.sub(pattern, '*', 'A3C9 and C1B17'))**
###### * [and ]*
21.3 Summary
There is a lot to remember. |
Here is a summary:
Expression Description
[] any of the characters inside the brackets
. any character except the newline
+ 1 or more of the preceding
- 0 or more of the preceding
? |
0 or 1 of the preceding
{m} exactly m of the preceding
{m,n} between m and n (inclusive) of the preceding
? |
following +, *, ?, {m}, and {m,n} — take as few as possible
\ escape special characters
| “or”
^ (at start of pattern) match just the first occurrence
$ (at end of pattern) match just the last occurrence
\d \D any digit (non-digit)
\w \W any letter or number (non-letter or -number)
\s \S any whitespace (non-whit... |
match newlines, too
(?x) flag to enable verbose style
-----
_21.3. |
SUMMARY_ 213
Here are some short examples:
Expression Description
'abc' the exact string abc
'[ABC]' an A, B, or C
'[a-zA-Z][0-9]' match a letter followed by a digit
'[a..]' a followed by any two characters (except newlines)
'a+' one or more a’s
'a*' any number of a’s, even none
'a?' zero or one a
'a{2}' exac... |
All of our matching is done from the left and does not consider overlaps. For
instance, we have the following:
re.sub('aba', '*', 'abababa')
-----
214 _CHAPTER 21. |
REGULAR EXPRESSIONS_
###### 21.4 Groups
Using parentheses around part of an expression creates a group that contains the text that matches a
pattern. |
You can use this to do more sophisticated substitutions. |
Here is an example that converts
to lowercase every capital letter that is followed by a lowercase letter:
**def modify(match):**
letters = match.group()
**return letters.lower()**
re.sub(r'([A-Z])[a-z]', modify, 'PEACH Apple ApriCot')
###### PEACH apple apricot
The modify function ends up getting called three t... |
The
re.sub function automatically sends to the modify function a Match object, which we name
match. This object contains information about the matching text. |
The object’s group method
returns the matching text itself.
If instead of match.group, we use match.groups, then we can further break down the match
according the groups defined by the parentheses. |
Here is an example that matches a capital letter
followed by a digit and converts each letter to lowercase and adds 10 to each number:
**def modify(match):**
letter, number = match.groups()
**return letter.lower() + str(int(number)+10)**
re.sub(r'([A-Z])(\d)', modify, 'A1 + B2 + C7')
###### a11 + b12 + c17
The g... |
For instance, in the above program the
tuples returned are shown below:
First match: ('A', '1')
Second match: ('B', '2')
Third match: ('C', '7')
Note also that we can get at this information by passing arguments to match.group. |
For the first
match, match.group(1) is 'A' and match.group(2) is 1.
###### 21.5 Other functions
- sub — We have seen many examples of sub. |
One thing we haven’t mentioned is that there
is an optional argument count, which specifies how many matches (from the left) to make.
Here is an example:
re.sub(r'a', '*', 'ababababa', count=2)
-----
_21.5. |
OTHER FUNCTIONS_ 215
- findall — The findall function returns a list of all the matches found. |
Here is an example:
re.findall(r'[AB]\d', 'A3 + B2 + A9')
As another example, to find all the words in a string, you can do the following:
re.findall(r'\w+', s)
This is better than using s.split() because split does not handle punctuation, while the
regular expression does.
- split — The split function is anal... |
The regular expression version allows us to split on something more general than the string method does. |
Here
is an example that splits an algebraic expression at + or -.
re.split(r'\+|\-', '3x+4y-12x^2+7')
- match and search — These are useful if you just want to know if a match occurs. |
The
difference between these two functions is match only checks to see if the beginning of the
string matches the pattern, while search searches through the string until it finds a match.
Both return None if they fail to find a match and a Match object if they do find a match. |
Here
are examples:
**if (re.match(r'ZZZ', 'abc ZZZ xyz')):**
**print('Match found at beginning.')**
**else:**
**print('No match at beginning')**
**if (re.search(r'ZZZ', 'abc ZZZ xyz')):**
**print('Match found in string.')**
**else:**
**print('No match found.')**
###### No match at beginning. |
Match found in string.
The Match object returned by these functions has group information in it. |
Say we have the
following:
a=re.search(r'([ABC])(\d)', '= A3+B2+C8')
a.group()
a.group(1)
a.group(2)
'A3'
'A'
'3'
Remember that re.search will only report on the first match it finds in the string.
-----
216 _CHAPTER 21. |
REGULAR EXPRESSIONS_
- finditer — This returns an iterator of Match objects that we can loop through, like below:
**for s in re.finditer(r'([AB])(\d)', 'A3+B4'):**
**print(s.group(1))**
Note that this is a little more general than the findall function in that findall returns the
matching strings, whereas findite... |
Here is an example:
pattern = re.compile(r'[AB]\d')
pattern.findall('A3+B4+C9+D8',2,6)
###### ['B4']
21.6 Examples
**Roman Numerals** Here we use regular expressions to convert Roman numerals into ordinary
numbers.
|man Numerals Here we use regular expressions to convert Roman numerals into ordinary mbers.|Col2|
... |
(CD)?(D)?(C{0,3}) (XC)?(XL)?(L)?(X{0,3}) (IX)?(IV)?(V)?(I{0,3})""") num = input('Enter Roman numeral: ').upper() m = pattern.match(num) sum = 0 for x in m.groups():||
-----
_21.6. |
EXAMPLES_ 217
**if x!=None and x!='':**
**if x in ['CM', 'CD', 'XC', 'XL', 'IX', 'IV']:**
**sum+=d[x]**
**elif x[0] in 'MDCLXVI':**
**sum+=d[x[0]]*len(x)**
**print(sum)**
###### Enter Roman numeral: MCMXVII 1917
The regular expression itself is fairly straightforward. |
It looks for up to three M’s, followed by zero
or one CM’s, followed by zero or one CD’s, etc., and stores each of those in a group. |
The for loop
then reads through those groups and uses a dictionary to add the appropriate values to a running
sum.
**Dates** Here we use a regular expression to take a date in a verbose format, like February 6, 2011,
and convert it an abbreviated format, mm/dd/yy (with no leading zeroes). |
Rather than depend
on the user to enter the date in exactly the right way, we can use a regular expression to allow for
variation and mistakes. |
For instance, this program will work whether the user spells out the whole
month name or abbreviates it (with or with a period). |
Capitalization does not matter, and it also
does not matter if they can even spell the month name correctly. They just have to get the first three
letters correct. |
It also does not matter how much space they use and whether or not they use a
comma after the day.
**import re**
d = {'jan':'1', 'feb':'2', 'mar':'3', 'apr':'4',
'may':'5', 'jun':'6', 'jul':'7', 'aug':'8',
'sep':'9', 'oct':'10', 'nov':'11', 'dec':'12'}
date = input('Enter date: ')
m = re.match('([A-Za-z]+)\.?\s*(\d... |
6, 2011 2/6/11
The first part of the regular expression, ([A-Za-z]+)\.? takes care of the month name. It matches
however many letters the user gives for the month name. The \.? |
matches either 0 or 1 periods
after the month name, so the user can either enter a period or not. The parentheses around the
letters save the result in group 1.
Next we find the day: \s*(\d{1,2}). |
The first part \s* matches zero or more whitespace characters, so it doesn’t matter how much space the user puts between the month and day. |
The rest
matches one or two digits and saves it in group 2.
|iation and mistakes. |
For instance, this program will work whether the user spells out the whole nth name or abbreviates it (with or with a period). |
Capitalization does not matter, and it also es not matter if they can even spell the month name correctly. They just have to get the first three ers correct. |
It also does not matter how much space they use and whether or not they use a mma after the day.|Col2|
|---|---|
|||
|import re d = {'jan':'1', 'feb':'2', 'mar':'3', 'apr':'4', 'may':'5', 'jun':'6', 'jul':'7', 'aug':'8', 'sep':'9', 'oct':'10', 'nov':'11', 'dec':'12'} date = input('Enter date: ') m = re.match('([A-Za-z]... |
REGULAR EXPRESSIONS_
The rest of the expression,,?\s*(\d{4}), finds the year. Then we use the results to create the
abbreviated date. |
The only tricky part here is the first part, which takes the month name, changes
it to all lowercase, and takes only the first three characters and uses those as keys to a dictionary.
This way, as long as the user correctly spells the first three letters of the month name, the program
will understand it.
-----
### C... |
Here are
most of them:
Function Description
sin, cos, tan trig functions
asin, acos, atan inverse trig functions
atan2(y,x) gives arctan( _y/x) with proper sign behavior_
sinh, cosh, tanh hyperbolic functions
asinh, acosh, atanh inverse hyperbolic functions
log, log10 natural log, log base 10
log1p log(1+x), mo... |
MATH_
**Note** Note that the floor and int functions behave the same for positive numbers, but differently for negative numbers. For instance, floor(3.57) and int(3.57) both return the integer 3. |
However, floor(-3.57) returns -4, the greatest integer less than or equal to -3.57, while
**int(-3.57) returns -3, which is obtained by throwing away the decimal part of the number.**
###### atan2 The atan2 function is useful for telling the angle between two points. |
Let x and y be
the distances between the points in the x and y directions. The tangent of the angle in the picture
below is given by y/x. |
Then arctan( _y/x) gives the angle itself._
But if the angle were 90[◦], this would not work as x would be 0. We would also need special cases
to handle when x < 0 and when y < 0. |
The atan2 function handles all of this. Doing atan2(y,x)
will return arctan( _y/x) with all of the cases handled properly._
The atan2 function returns the result in radians. |
If you would like degrees, do the following:
angle = math.degrees(atan2(y,x))
The resulting angle from atan2 is between _π and π (_ 180[◦] and 180[◦]). |
If you would like it between
_−_ _−_
0 and 360[◦], do the following:
angle = math.degrees(atan2(y,x))
angle = (angle+360) % 360
###### 22.2 Scientific notation
Look at the following code:
100.1**10
###### 1.0100451202102516e+20
The resulting value is displayed in scientific notation. |
It is 1.0100451202102516 10[20]. The e+20
_×_
stands for 10[20]. Here is another example:
_×_
.15**10
###### 5.7665039062499975e-09
This is 5.7665039062499975 10[−][9].
_×_
-----
_22.3. |
COMPARING FLOATING POINT NUMBERS_ 221
###### 22.3 Comparing floating point numbers
In Section 3.1 we saw that some numbers, like .1, are not represented exactly on a computer. |
Mathematically, after the code below executes, x should be 1, but because of accumulated errors, it is
actually 0.9999999999999999.
x = 0
**for i in range(10):**
x+=.1
This means that the following if statement will turn out False:
**if x==1:**
A more reliable way to compare floating point numbers x and y is to ... |
Here is a simple example of it in
action:
**from fractions import Fraction**
r = Fraction(3, 4)
s = Fraction(1, 4)
**print(r+s)**
###### Fraction(1, 1)
You can do basic arithmetic with Fraction objects, as well as compare them, take their absolute
values, etc. |
Here are some further examples:
r = Fraction(3, 4)
s = Fraction(2, 8)
**print(s)**
**print(abs(2*r-3))**
**if r>s:**
**print('r is larger')**
###### Fraction(1,4) Fraction(3,2) r is larger
Note that Fraction automatically converts things to lowest terms. |
The example below shows how
to get the numerator and denominator:
r = Fraction(3,4)
r.numerator
r.denominator
-----
222 _CHAPTER 22. |
MATH_
###### 3 4
**Converting to and from floats** To convert a fraction to a floating point number, use float, like
below:
**float(Fraction(1, 8))**
###### 0.125
On the other hand, say we want to convert 0.3 to a fraction. |
Unfortunately, we should not do
Fraction(.3) because, as mentioned, some numbers, including .3, are not represented exactly
on the computer. |
In fact, Fraction(.3) returns the following Fraction object:
###### Fraction(5404319552844595, 18014398509481984)
Instead, use string notation, like below:
Fraction('.3')
**Limiting the denominator** One useful method is limit_denominator. |
For a given Fraction
object, limit_denominator(x) finds the closest fraction to that value whose denominator does
not exceed x. |
Here is some examples:
Fraction('.333').limit_denominator(100)
Fraction('.333').limit_denominator(1000)
Fraction('3.14159').limit_denominator(1000)
###### Fraction(1, 3) Fraction(333, 1000) Fraction(355, 113)
The last example returns a pretty close fractional approximation to π. |
It is off by less than 0.0000003.
**Greatest common divisor** The fractions module contains a useful function called gcd that
returns the greatest common divisor of two numbers. |
Here is an example:
**from fractions import gcd**
**print('The largest factor 35 and 21 have in common is', gcd(35, 21))**
###### The largest factor 35 and 21 have in common is 7
22.5 The decimal module
Python has a module called decimal for doing exact calculations with decimal numbers. |
As we’ve
noted a few times now, some numbers, such as .3, cannot be represented exactly as a float. Here is
-----
_22.5. |
THE DECIMAL MODULE_ 223
how to get an exact decimal representation of .3:
**from decimal import Decimal**
Decimal('.3')
###### Decimal('0.3')
The string here is important. |
If we leave it out, we get a decimal that corresponds with the inexact
floating point representation of .3:
Decimal(.3)
**Math** You can use the usual math operators to work with Decimal objects. |
For example:
Decimal(.34) + Decimal(.17)
Here is another example:
Decimal(1) / Decimal(17)
The mathematical functions exp, ln, log10, and sqrt are methods of decimal objects. |
For instance, the following gives the square root of 2:
Decimal(2).sqrt()
Decimal objects can also be used with the built in max, min, and sum functions, as well as converted
to floats with float and strings with str.
**Precision** By default Decimal objects have 28-digit precision. |
To change it to, say, five digitprecision, use the getcontext function.
**from decimal import getcontext**
getcontext().prec = 5
_�_
Here is an example that prints out 100 digits of
getcontext().prec = 100
Decimal(2).sqrt()
2:
-----
224 _CHAPTER 22. |
MATH_
There is theoretically no limit to the precision you can use, but the higher the precision, the more
memory is required and the slower things will run. |
In general, even with small precisions, Decimal
objects are slower than floating point numbers. |
Ordinary floating point arithmetic is enough for
most problems, but it is nice to know that you can get higher precision if you ever need it.
There is a lot more to the decimal module. |
See the Python documentation [1].
###### 22.6 Complex numbers
Python has a data type for complex numbers.
_�_
In math, we have i = _−1. The number i is called an imaginary number. |
A complex number is a_
number of the form a + bi, where a and b are real numbers. The value a is called the real part, and
_b is the imaginary part. |
In electrical engineering, the symbol j is used in place of i, and in Python j_
is used for imaginary numbers. |
Here are a couple of examples of creating complex numbers:
x = 7j
x = 1j
x = 3.4 + .3j
x = complex(3.4, .3)
If a number ends in a j or J, Python treats it as a complex number.
Complex numbers have methods real() and imag() which return the real and imaginary parts
of the number. |
The conjugate method returns the complex conjugate (the conjugate of a + bi is
_a_ _bi)._
_−_
The cmath module contains many of the same functions as the math module, except that they work
with complex arguments. |
The functions include regular, inverse, and hyperbolic trigonometric
functions, logarithms and the exponential function. |
It also contains two functions, polar and
rect, for converting between rectangular and polar coordinates:
cmath.polar(3j)
cmath.rect(3.0, 1.5707963267948966)
###### (3.0, 1.5707963267948966) (1.8369701987210297e-16+3j)
Complex numbers are fascinating, though not all that useful in day-to-day life. |
One nice application, however, is fractals. Here is a program that draws the famous Mandelbrot set. |
The program
requires the PIL and Python 2.6 or 2.7.
|mplex numbers are fascinating, though not all that useful in day-to-day life. One nice applica- n, however, is fractals. |
Here is a program that draws the famous Mandelbrot set. |
The program uires the PIL and Python 2.6 or 2.7.|Col2|
|---|---|
|||
|from Tkinter import * from PIL import Image, ImageTk, ImageDraw def color_convert(r, g, b): return '#{0:02x}{1:02x}{2:02x}'.format(int(r*2.55),int(g*2.55), int(b*2.55)) max_iter=75||
-----
_22.6. |
COMPLEX NUMBERS_ 225
xtrans=-.5
ytrans=0
xzoom=150
yzoom=-150
root = Tk()
canvas = Canvas(width=300, height=300)
canvas.grid()
image=Image.new(mode='RGB',size=(300,300))
draw = ImageDraw.Draw(image)
**for x in range(300):**
c_x = (x-150)/float(xzoom)+xtrans
**for y in range(300):**
c = complex(c_x, (y-150)/float(y... |
There are ways to speed it up somewhat, but Python is unfortunately slow for these kinds of things.
-----
226 _CHAPTER 22. |
MATH_
###### 22.7 More with lists and arrays
**Sparse lists** A 10,000,000 10,000,000 list of integers requires several hundred terabytes of storage,
_×_
far more than most hard drives can store. |
However, in many practical applications, most of the
entries of a list are 0. This allows us to save a lot of memory by just storing the nonzero values along
with their locations. |
We can do this using a dictionary whose keys are the locations of the nonzero
elements and whose values are the values stored in the array at those locations. |
For example,
suppose we have a two-dimensional list L whose entries are all zero except that L[10][12] is 47
and L[100][245] is 18. |
Here is a the dictionary that we would use:
d = {(10,12): 47, (100,245): 18}
**The array module** Python has a module called array that defines an array object that behaves
a lot like a list, except that its elements must all be the same type. |
The benefit of array over lists is
more efficient memory usage and faster performance. |
See the Python documentation [1] for more
about arrays.
**The NumPy and SciPy libraries** If you have any serious mathematical or scientific calculations
[to do on arrays, you may want to consider the NumPy library. |
It is easy to download and install.](http://numpy.scipy.org/)
From the NumPy user’s guide:
NumPy is the fundamental package for scientific computing in Python. |
It is a Python
library that provides a multidimensional array object, various derived objects (such as
masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra... |
This time from the SciPy user’s guide:](http://scipy.org/)
SciPy is a collection of mathematical algorithms and convenience functions built on
the NumPy extension for Python. |
It adds significant power to the interactive Python
session by exposing the user to high-level commands and classes for the manipulation and visualization of data. |
With SciPy, an interactive Python session becomes a
data-processing and system-prototyping environment rivaling sytems such as MATLAB, IDL, Octave, R-Lab, and SciLab.
###### 22.8 Random numbers
**How Python generates random numbers** The random number generator that Python uses is
called the Mersenne Twister. |
It is reliable and well-tested. It is a deterministic generator, meaning
-----
_22.8. RANDOM NUMBERS_ 227
that it uses a mathematical process to generate random numbers. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.