Text stringlengths 1 9.41k |
|---|
This is a third-party module that converts Python programs to cutables. As of now, it is only available for Python 2. It can be a little tricky to use. |
Here is a pt that you can use once you have py2exe installed.|Col2|
|---|---|
|||
|import os program_name = raw_input('Enter name of program: ') if program_name[-3:]!= '.py': program_name+='.py' with open('temp_py2exe.py', 'w') as fp: s = 'from distutils.core import setup\n' s += "import py2exe\nsetup(console=['" s += ... |
MISCELLANEOUS TOPICS III_
-----
### Chapter 20
## Useful modules
Python comes with hundreds of modules that do all sorts of things. |
There are also many thirdparty modules available for download from the internet. |
This chapter discusses a few modules
that I have found useful.
###### 20.1 Importing modules
There are a couple of different ways to import modules. |
Here are several ways to import some
functions from the Random module.
**from random import randint, choice**
**from random import ***
**import random**
1. |
The first way imports just two functions from the module.
2. The second way imports every function from the module. |
You should usually avoid doing this, as the module may contain some names that will interfere with your own variable
names. |
For instance if your program uses a variable called total and you import a module
that contains a function called total, there can be problems. |
Some modules, however, like
tkinter, are fairly safe to import this way.
3. The third way imports an entire module in a way that will not interfere with your variable
names. |
To use a function from the module, preface it with random followed by a dot. |
For
instance: random.randint(1,10).
**Changing module names** The as keyword can be used to change the name that your program
uses to refer to a module or things from a module. |
Here are three examples:
**import numpy as np**
199
-----
200 _CHAPTER 20. |
USEFUL MODULES_
**from itertools import combinations_with_replacement as cwr**
**from math import log as ln**
**Location** Usually, import statements go at the beginning of the program, but there is no restriction. |
They can go anywhere as long as they come before the code that uses the module.
**Getting help** To get help on a module (say the random module) at the Python shell, import it
using the third way above. |
Then dir(random) gives a list of the functions and variables in the
module, and help(random) will give you a rather long description of what everything does. |
To
get help on a specific function, like randint, type help(random.randint).
###### 20.2 Dates and times
The time module has some useful functions for dealing with time.
###### sleep The sleep function pauses your program for a specified amount of time (in seconds).
For instance, to pause your program for 2 seconds ... |
Here is an example:
**from time import time**
start = time()
_# do some stuff_
**print('It took', round(time()-start, 3), 'seconds.')**
For another example, see Section 17.6, which shows how to put a countdown timer into a GUI.
The resolution of the time() function is milliseconds on Windows and microseconds on Linu... |
If you want millisecond resolution, use the following
print statement:
**print('{:.3f} seconds'.format(time()-start))**
You can use a little math on this to get minutes and hours. |
Here is an example:
t = time()-start
secs = t%60
mins = t//60
hours = mins//60
By the way, when you call time(), you get a rather strange value like 1306372108.045. |
It is the
number of seconds elapsed since January 1, 1970.
-----
_20.2. DATES AND TIMES_ 201
**Dates** The module datetime allows us to work with dates and times together. |
The following
line creates a datetime object that contains the current date and time:
**from datetime import datetime**
d = datetime(1,1,1).now()
The datetime object has attributes year, month, day, hour, minute, second, and microsecond.
Here is a short example:
d = datetime(1,1,1).now()
**print('{}:{:02d} {}/{}/{}'... |
To get 12-hour format, you can do the following:
am_pm = 'am' if d.hour<12 else 'pm'
**print('{}:{}{}'.format(d.hour%12, d.minute, am_pm))**
An alternative way to display the date and time is to use the strftime method. |
It uses a variety
of formatting codes that allow you to display the date and time, including information about the
day of the week, am/pm, etc.
Here are some of the formatting codes:
Code Description
%c date and time formatted according to local conventions
%x, %X %x is the date, and %X is the time, both formatted ... |
USEFUL MODULES_
###### 02/01/11 07:33:14 07AM on February 01
The leading zeros are a little annoying. |
You could combine strftime with the first way we learned
to get nicer output:
**print(d.strftime('{}%p on %B {}').format(d.hour%12, d.day))**
You can also create a datetime object. |
When doing so, you must specify the year, month, and day.
The other attributes are optional. |
Here is an example:
d = datetime(2011, 2, 1, 7, 33)
e = datetime(2011, 2, 1)
You can compare datetime objects using the <, >, ==, and != operators. |
You can also do arithmetic
on datetime objects, though we won’t cover it here. |
In fact, there is a lot more you can do with
dates and times.
Another nice module is calendar which you can use to print out calendars and do more sophisticated calculations with dates.
###### 20.3 Working with files and directories
The os module and the submodule os.path contain functions for working with files and... |
If not, you have to specify the directory, like below:
s = open('c:/users/heinold/desktop/file.txt').read()
If you have a lot of files that you need to read, all in the same directory, you can use os.chdir to
change the directory. |
Here is an example:
os.chdir('c:/users/heinold/desktop/')
s = open('file.txt').read()
**Getting the current directory** The function getcwd returns the path of current directory. |
It will
be the directory your program is in or the directory you changed it to with chdir.
**Getting the files in a directory** The function listdir returns a list of the entries in a directory,
including all files and subdirectories. |
If you just want the files and not the subdirectories or viceversa, the os.path module contains the functions isfile and isdir to tell if an entry is a file or a
-----
_20.3. |
WORKING WITH FILES AND DIRECTORIES_ 203
directory. |
Here is an example that searches through all the files in a directory and prints the names
of those files that contain the word 'hello'.
**import os**
directory = 'c:/users/heinold/desktop/'
files = os.listdir(directory)
**for f in files:**
**if os.path.isfile(directory+f):**
s = open(directory+f).read()
**if 'hello... |
Just be careful here.
Function Description
mkdir create a directory
rmdir remove a directory
remove delete a file
rename rename a file
The first two functions take a directory path as their only argument. |
The remove function takes a
single file name. |
The first argument of rename is the old name and the second argument is the new
name.
**Copying files** There is no function in the os module to copy files. |
Instead, use the copy function
in the shutil module. |
Here is an example that takes all the files in a directory and makes a copy
of each, with each copied file’s name starting with Copy of :
**import os**
**import shutil**
directory = 'c:/users/heinold/desktop/'
files = os.listdir(directory)
**for f in files:**
**if os.path.isfile(directory+f):**
shutil.copy(directory... |
Different operating systems have different conventions for how
they handle paths, and the functions in os.path allow your program to work with different operating systems without having to worry about the specifics of each one. |
Here are some examples
(on my Windows system):
**print(os.path.split('c:/users/heinold/desktop/file.txt'))**
**print(os.path.basename('c:/users/heinold/desktop/file.txt'))**
**print(os.path.dirname('c:/users/heinold/desktop/file.txt'))**
|ectory. |
Here is an example that searches through all the files in a directory and prints the names hose files that contain the word 'hello'.|Col2|
|---|---|
|||
|import os directory = 'c:/users/heinold/desktop/' files = os.listdir(directory) for f in files: if os.path.isfile(directory+f): s = open(directory+f).read() if 'hello... |
Instead, use the copy function he shutil module. |
Here is an example that takes all the files in a directory and makes a copy ach, with each copied file’s name starting with Copy of :|Col2|
|---|---|
|||
|import os import shutil directory = 'c:/users/heinold/desktop/' files = os.listdir(directory) for f in files: if os.path.isfile(directory+f): shutil.copy(directory+f... |
USEFUL MODULES_
**print(os.path.join('directory', 'file.txt'))**
###### ('c:/users/heinold/desktop', 'file.txt') file.txt c:/users/heinold/desktop directory\\file.txt
Note that the standard separator in Windows is the backslash. |
The forward slash also works.
Finally, two other functions you might find helpful are the exists function, which tests if a file
or directory exists, and getsize, which gets the size of a file. |
There are many other functions in
os.path. |
See the Python documentation [1] for more information.
###### os.walk The os.walk function allows you to scan through a directory and all of its subdirectories. |
Here is a simple example that finds all the Python files on my desktop or in subdirectories
of my desktop:
**for (path, dirs, files) in os.walk('c:/users/heinold/desktop/'):**
**for filename in files:**
**if filename[-3:]=='.py':**
**print(filename)**
###### 20.4 Running and quitting programs
**Running programs*... |
Here is an example:
**import os**
os.chdir('c:/users/heinold/desktop')
os.system('file.exe')
The system function can be used to run commands that you can run at a command prompt. |
Another way to run your programs is to use the execv function.
**Quitting your program** The sys module has a function called exit that can be used to quit your
program. |
Here is a simple example:
**import sys**
ans = input('Quit the program?')
**if ans.lower() == 'yes'**
sys.exit()
###### 20.5 Zip files
A zip file is a compressed file or directory of files. |
The following code extracts all the files from a
zip file, filename.zip, to my desktop:
-----
_20.6. |
GETTING FILES FROM THE INTERNET_ 205
**import zipfile**
z = zipfile.ZipFile('filename.zip')
z.extractall('c:/users/heinold/desktop/)
###### 20.6 Getting files from the internet
For getting files from the internet there is the urllib module. |
Here is a simple example:
**from urllib.request import urlopen**
page = urlopen('http://www.google.com')
s = page.read().decode()
The urlopen function returns an object that is a lot like a file object. |
In the example above, we use
the read() and decode() methods to read the entire contents of the page into a string s.
The string s in the example above is filled with the text of an HTML file, which is not pretty to read.
There are modules in Python for parsing HTML, but we will not cover them here. |
The code above
is useful for downloading ordinary text files of data from the internet.
[For anything more sophisticated than this, consider using the third party requests library.](http://docs.python-requests.org/en/latest/index.html)
###### 20.7 Sound
An easy way to get some simple sounds in your program is to use... |
It only
works with Windows, however. One function in winsound is Beep which can be used to play a
tone at a given frequency for a given amount of time. |
Here is an example that plays a sound of 500
Hz for 1 second.
**from winsound import Beep**
Beep(500,1000)
The first argument to Beep is the frequency in Hertz and the second is the duration in milliseconds.
Another function in winsound is PlaySound, which can be used to play WAV files. |
Here is an
example:
**from winsound import PlaySound**
Playsound('soundfile.wav', 'SND_ALIAS')
On the other hand, If you have Pygame installed, it is pretty easy to play any type of common
sound file. |
This is shown below, and it works on systems other than Windows:
**import pygame**
pygame.mixer.init(18000,-16,2,1024)
sound = pygame.mixer.Sound('soundfile.wav')
sound.play()
-----
206 _CHAPTER 20. |
USEFUL MODULES_
###### 20.8 Your own modules
Creating your own modules is easy. Just write your Python code and save it in a file. |
You can then
import your module using the import statement.
-----
### Chapter 21
## Regular expressions
The replace method of strings is used to replace all occurrences of one string with another, and
the index method is used to find the first occurrence of a substring in a string. |
But sometimes you
need to do a more a sophisticated search or replace. For example, you may need to find all of the
occurrences of a string instead of just the first one. |
Or maybe you want to find all occurrences of
two letters followed by a number. Or perhaps you need to replace every 'qu' that is at the start
of a word with 'Qu'. |
This is what regular expressions are for. Utilities for working with regular
expressions are found in the re module.
There is some syntax to learn in order to understand regular expressions. |
Here is one example to
give you an idea of how they work:
**import re**
**print(re.sub(r'([LRUD])(\d+)', '***', 'Locations L3 and D22 full.'))**
###### Locations *** and *** full.)
This example replaces any occurrence of an L, R, U, or D followed by one or more digits with
'***'.
###### 21.1 Introduction
sub The ... |
All of the upcoming examples will be shown with sub, but there are other
things we can do with regular expressions besides substituting. |
We will get to those after discussing
the syntax of regular expressions.
207
-----
208 _CHAPTER 21. REGULAR EXPRESSIONS_
**Raw strings** A lot of the patterns use backslashes. |
However, backslashes in strings are used for
escape characters, like the newline, \n. To get a backslash in a string, we need to do \\. This
can quickly clutter up a regular expression. |
To avoid this, our patterns will be raw strings, where
backslashes can appear as is and don’t do anything special. |
To mark a string as a raw string, preface
it with an r like below:
s = r'This is a raw string. |
Backslashes do not do anything special.'
###### 21.2 Syntax
**Basic example** We start with a regular expression that mimics the replace method of strings.
Here is a example of using replace to replace all occurrences of abc with *:
'abcdef abcxyz'.replace('abc', '*')
###### *[def ]*[xyz]
Here is the regular expr... |
Here are some
further examples of ranges:
Range Description
[A-Z] any capital letter
[0-9] any digit
[A-Za-z0-9] any letter or digit
A slightly shorter way to match any digit is \d, instead of [0-9].
**Matching any character** Use a dot to match (almost) any character. |
Here is an example:
re.sub(r'A.B', '*', 'A2B AxB AxxB A$B')
-----
_21.2. |
SYNTAX_ 209
###### * * [AxxB ]*
The pattern matches an A followed by almost any single character followed by a B.
Exception: The one character not matched by the dot is the newline character. |
If you need that to
be matched, too, put ?s at the start of your pattern.
**Matching multiple copies of something** Here is an example where we match an A followed by
one or more B’s:
re.sub(r'AB+', '*', 'ABC ABBBBBBC AC)
###### *[C ]*[C AC]
We use the + character to indicate that we want to match one or more B’s h... |
There are similar
things we can use to specify different numbers of B’s here. For instance, using * in place of + will
match zero or more B’s. |
(This means that AC in the example above would be replaced by *C because
A counts as an A followed by zero B’s.) Here is a table of what you can do:
Code Description
+ match 1 or more occurrences
- match 0 or more occurrences
? |
match 0 or 1 occurrence
{m} match exactly m occurrences
{m,n} match between m and n occurrences, inclusive
Here is an example that matches an A followed by three to six B’s:
re.sub(r'AB{3,6}', '*', 'ABB ABBB ABBBB ABBBBBBBBB')
'ABB * * *BBB'
Here, we do not match ABB because the A is only followed by two B’s. |
The next two pieces get
matched, as the A is followed by three B’s in the second term, and four B’s in the third. In the last
piece, there is an A followed by nine B’s. |
What gets matched isthe A along with the first six B’s.
Note that the matching in the last piece above is greedy; that is, it takes as many B’s as it is allowed.
It is allowed to take between three and six B’s, and it takes all six. |
To get the opposite behavior, to
get it take as few B’s as allowed, add a ?, like below:
re.sub(r'AB{3,6}?', '*', 'ABB ABBB ABBBB ABBBBBBBBB')
'ABB * * *BBBBBB'
The ? |
can go after any of the numeric specifiers, like +?, -?, ??, etc.
**The | character** The | character acts as an “or.” Here is an example:
-----
210 _CHAPTER 21. |
REGULAR EXPRESSIONS_
re.sub(r'abc|xyz', '*', 'abcdefxyz123abc')
'*def*123*'
In the above example, every time we encounter an abc or an xyz, we replace it with an asterisk.
**Matching only at the start or end** Sometimes you don’t want to match every occurrence of something, maybe just the first or the last occurren... |
To match just the first occurrence of something,
start the pattern off with the ^ character. To match just the last occurrence, end the pattern with the
$ character. |
Here are some examples:
re.sub('^abc', '*', 'abcdefgabc')
re.sub('abc$', '*', 'abcdefgabc')
###### *[defgabc] abcdefg*
**Escaping special characters** We have seen that + and * have special meanings. |
What if we need
to match a plus sign? To do so, use the backslash to escape it, like \+. |
Here is an example:
re.sub(r'AB\+', '*', 'AB+C')
###### *[C]
Also, in a pattern, \n represents a newline.
Just a note again about raw strings—if we didn’t use them for the patterns, every backslash would
have to be doubled. |
For instance, r'AB\+' would have to be 'AB\\+.
**Backslash sequences**
- \d matches any digit, and \D matches any non-digit. |
Here is an example:
re.sub(r'\d', '*', '3 + 14 = 17')
re.sub(r'\D', '*', '3 + 14 = 17')
###### * [+ ]** [= ]** 3***14***17
- \w matches any letter or number, and \W matches anything else. |
Here is an example:
re.sub(r'\w', '*', 'This is a test. Or is it?')
re.sub(r'\W', '*', 'This is a test. Or is it?')
'**** ** * ****. |
** ** **[?][']
'This*is*a*test***Or*is*it*'
This is a good way to work with words.
- \s matches whitespace, and \S matches non-whitespace. Here is an example:
-----
_21.2. |
SYNTAX_ 211
re.sub(r'\s', '*', 'This is a test. Or is it?')
re.sub(r'\S', '*', 'This is a test. |
Or is it?')
'This*is*a*test.**Or*is*it?'
'**** ** * ***** ** ** ***[']
**Preceding and following matches** Sometimes you want to match things if they are preceded or
followed by something.
Code Description
(?=) matches only if followed by
(?!) matches only if not followed by
(?<=) matches only if preceded by
(?<... |
We
look at a few of them here.
- (?i) — This is to ignore case. Here is an example:
re.sub('(?i)ab', '*', 'ab AB')
###### * *
- (?s) — Recall the . |
character matches any character except a newline. This flag makes it
match newline characters, too.
-----
212 _CHAPTER 21. |
REGULAR EXPRESSIONS_
- (?x) — Regular expressions can be long and complicated. This flag allows you to use a more
verbose, multi-line format, where whitespace is ignored. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.