Day04 -- Python module, day04python
I. Module Introduction
A module is a set of code that implements a function. For example, several. py files can form a set of code, that is, a module. Common modules include the OS module (system-related) and file module (file operation-related)
There are three main modules:
- Custom module: a module composed of Python files.
- Third-party module: a module written by others, that is, a module provided by a third party
- Built-in modules: python built-in modules
Ii. Module Import
There are several ways to import a module, including direct or module import.
import modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename from module.xx.xx import *
The import module tells the Python interpreter to explain the py file.
- Import a py file. The Interpreter explains the py file.
- Import a package. The Interpreter explains the _ init _. py file under the package [py2.7]
Note:
When importing a module, the default read path isSys. path. You can view the default path of the current system using the following method:
Import sysprint sys. path
The output result is as follows:
['', '/Usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg', '/usr/lib/python2.7/site-packages/setuptools-19.4-py2.7.egg ', '/usr/lib/python2.7/site-packages/Django-1.8.8-py2.7.egg', '/usr/lib/python2.7/site-packages/django_pagination-1.0.7-py2.7.egg', '/usr/lib64/python27.zip ', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk ', '/usr/lib64/python2.7/lib-old','/usr/lib64/python2.7/lib-dynload ','/usr/lib64/python2.7/site-packages ', '/usr/lib/python2.7/site-packages']
When importing a module, if it is no longer in the default path, you can add it to the default path using the following methods:
import sysimport osproject_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(project_path)
Iii. Common built-in modules
The built-in modules are built-in functions of Python. You need to import them before using them.
1. sys module
Provides operations related to the python interpreter.
Import sys
Sys. argv command line parameter List. The first element is the program path sys. exit (n) exit the program. exit (0) sys when the program Exits normally. obtain the version information of the Python interpreter sys. the maximum Int value of maxint sys. path: return the search path of the module. during initialization, use the value of the PYTHONPATH environment variable sys. platform returns the name of the operating system platform sys. sys. stdout output related sys. stderror errors
2. OS Module
Provides system-level operations
OS. getcwd () obtains the current working directory, that is, the operating directory path of the current python script. chdir ("dirname") changes the current script working directory, which is equivalent to cdos in shell. curdir returns the current directory :('. ') OS. pardir: Get the string name of the parent directory of the current directory :('.. ') OS. makedirs ('dir1/dir2') can generate a multi-layer recursive directory OS. removedirs ('dirname1') if the directory is empty, it is deleted and recursive to the upper-level directory. If the directory is empty, it is deleted and OS is pushed accordingly. mkdir ('dirname') generates a single-level Directory, which is equivalent to mkdir dirnameos in shell. rmdir ('dirname') deletes a single-stage empty directory. If the directory is not empty, it cannot be deleted. An error is returned, which is equivalent to rmdir dirnameos in shell. listdir ('dirname') lists all files and subdirectories in a specified directory, including hidden files, and prints OS in list mode. r Emove () deletes a file OS. rename ("oldname", "new") rename the file/directory OS. stat ('path/filename ') to obtain the file/directory information OS. the specific path Separator of the sep operating system. The path separator is "\" in win, and the path separator is "/" in Linux. linesep: The line terminator used by the current platform. The line terminator is \ t \ n in win, and the line terminator is \ n in Linux. pathsep is the string OS used to split the file path. the name string indicates the current platform. Win-> 'nt '; Linux-> 'posix' OS. system ("bash command") runs the shell command to directly display the OS. environ obtains the OS environment variable. path. abspath (path) returns the absolute path OS of path normalization. path. split (path) splits the path into two groups: Directory and file name, and returns OS. path. dirname (path) returns the path directory. In fact, the first element OS. path. split (path) of OS. path. basename (path) returns the final file name of path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element of split (path), OS. path. exists (path) returns True if path exists. Returns Falseos if path does not exist. path. isabs (path) returns Trueos if path is an absolute path. path. isfile (path) returns True if path is an existing file. Otherwise, Falseos. path. isdir (path) is returned. If path is an existing Directory, True is returned. Otherwise, Falseos is returned. path. join (path1 [, path2 [,...]) if multiple paths are combined, the parameters before the first absolute path are ignored. path. getatime (path) returns the last access time OS of the file or directory pointed to by path. path. getmtime (path) returns the last modification time of the file or directory pointed to by path.
3. hashlib Module
Used for encryption-related operations, instead of the md5 module and sha module, mainly provides SHA1, sha1_, SHA256, SHA384, SHA512, MD5 Algorithm
import hashlib # ######## md5 ########hash = hashlib.md5()# help(hash.update)hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())print(hash.digest()) ######## sha1 ######## hash = hashlib.sha1()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())
Hashlib direct encryption may be used by the library to crack the password, so here we can encrypt it by customizing the key in the encryption algorithm. The specific example is as follows:
import hashlib # ######## md5 ######## hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))hash.update(bytes('admin',encoding="utf-8"))print(hash.hexdigest())
The Python built-in hmac module can further process the key and content we create, and then encrypt
import hmac h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))h.update(bytes('admin',encoding="utf-8"))print(h.hexdigest())
4. random Module
Module used to generate random numbers
Import random
Random. random () # random value 0.9151227988883402random.randint (1, 3) # random integer 3random between [m-n. randrange () # random integer 1random between [m-n. choice ('China') # random one character or list value's 'random. choice ([1, 5, 'abc']) 1random. sample ('hello', 2) # randomly retrieve N characters from the string ['h', 'L'] random. uniform () # retrieve the floating point number 7.797492134321265l = [, 5] From the interval (m, n) # change the ordered list to unordered random. shuffle (l) l [2, 4, 1, 5, 3]
Write a four-digit verification code program consisting of digits and letters: (# uppercase ascii: 65-90, lowercase letter: 97-122)
#! /Usr/bin/env python #-*-UTF-8-*-# Author: Rangle # uppercase letter ascii: 65-90, lowercase letter: 97-122import randomcheck_code = ''for I in range (4): num = random. randint (0, 3) if num = I: num1 = random. randint (0, 3) if num = num1: code = chr (random. randint (65, 90) else: code = chr (random. randint (97,122) else: code = random. randint (1, 9) check_code + = str (code) print (check_code)
5. re Module
Re provides operations related to regular expressions
Character:
. Match any character except linefeed
\ W matches letters, numbers, underscores, and Chinese characters
\ S matches any blank space character
\ D matching number
\ B matches the start or end of a word
^ Match the start of a string
$ End of matching string
Times:
* Repeated zero or more times
+ Repeat once or more times
? Zero or one repetition
{N} repeated n times
{N,} repeat n times or more times
{N, m} repeat n to m times
Match:
Match: matches from the starting position. If the match succeeds, an object is returned. If the match is not successful, None is returned.
Match (pattern, string, flags = 0)
# Match: match from the starting position. If the match succeeds, an object is returned. If the match fails, None match (pattern, string, flags = 0) is returned. # pattern: regular model # string: string to be matched # falgs: matching mode x verbose Ignore whitespace and comments for nicer looking RE's. I IGNORECASE Perform case-insensitive matching. m multiline "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. s dotall ". "matches any character at all, including the newline. a ascii For string patterns, make \ w, \ W, \ B, \ B, \ d, \ D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default ). for bytes patterns, this flag is the only available behaviour and needn't be specified. l locale Make \ w, \ W, \ B, \ B, dependent on the current locale. u unicode For compatibility only. ignored for string patterns (it is the default), and forbidden for bytes patterns.
Match syntax
# No group r = re. match ("h \ w +", origin) print (r. group () # obtain all matched results print (r. groups () # obtain the matching grouping result print (r. groupdict () # obtain the matching grouping results in the model # grouping # Why do we need to have groups? Extract the matched content (first match all the regular expressions, and then extract the locally matched content) r = re. match ("h (\ w + ).*(? P <name> \ d) $ ", origin) print (r. group () # obtain all matched results print (r. groups () # obtain the matching grouping result print (r. groupdict () # obtain the Demo of all groups in which the key is executed in the group matched in the model.
Match example
Search:
Search: browses the entire string to match the first one. If no matching is successful, None is returned.
Search (pattern, string, flags = 0)
# No group r = re. search ("a \ w +", origin) print (r. group () # obtain all matched results print (r. groups () # obtain the matching grouping result print (r. groupdict () # obtain the group results matching the model # group r = re. search ("a (\ w + ). *(? P <name> \ d) $ ", origin) print (r. group () # obtain all matched results print (r. groups () # obtain the matching grouping result print (r. groupdict () # obtain the demo of all groups in which the key is executed in the group matched in the model.
Search example
Findall:
Findall: get the list of non-repeated matches. If there is a group, it is returned in the form of a list, and each match is a string. If there are multiple groups in the model, it is returned in the form of a list, and each match is the ancestor;
Null matches will also be included in the results.
Findall (pattern, string, flags = 0)
# No group r = re. findall ("a \ w +", origin) print (r) # group origin = "hello alex bcd abcd lge acd 19" r = re. findall ("a (\ w *) c) (d)", origin) print (r) Demo
Findall example
Sub:
Replace the matched string at the specified position
Sub (pattern, repl, string, count = 0, flags = 0)
Pattern: regular model
Repl: string or executable object to be replaced
String: string to be matched
Count: Number of matched items
Flags: matching mode
# Origin = "hello alex bcd alex lge alex acd 19" r = re. sub ("a \ w +", "999", origin, 2) print (r)
Sub example
Split:
Split: Splits a string based on regular match.
Split (pattern, string, maxsplit = 0, flags = 0)
Pattern: regular model
String: string to be matched
Maxsplit: specifies the number of shards.
Flags: matching mode
# No group origin = "hello alex bcd alex lge alex acd 19" r = re. split ("alex", origin, 1) print (r) # grouping origin = "hello alex bcd alex lge alex acd 19" r1 = re. split ("(alex)", origin, 1) print (r1) r2 = re. split ("(al (ex)", origin, 1) print (r2) Demo
Split example
Common Regular Expression matching:
IP: ^ (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) (\. (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) {3} $ mobile phone number: ^ 1 [3 | 4 | 5 | 8] [0-9] \ d {8} $ Email: [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + (\. [a-zA-Z0-9 _-] +) +
6. serialization Module
Two modules used for serialization in Python
- Json is used for conversion between [String] and [python basic data type ].
- Pickle is used for conversion between [python-specific types] and [python Basic Data Types]
The Json module provides four functions: dumps, dump, loads, and load.
The pickle module provides four functions: dumps, dump, loads, and load.
#! /Usr/bin/env python #-*-UTF-8-*-# Author: Rangleimport jsonimport pickledata = {'k1 ': 123, 'k2 ': 'Lucy '} p_str = pickle. dumps (data) # convert data into a print (p_str) with open ('f: \ python_project \ Day03 \ test.txt ', 'wb + ') as fp: p_str = pickle. dump (data, fp) # convert data into strings recognized only by the Python language in a special form and write the data into the file j_str = json. dumps (data) # convert data into the print (j_str) string recognized by all programs in special form with open ('f: \ python_project \ Day03 \ test1.txt ', 'W + ') as fp: j_str = json. dump (data, fp) # convert data into strings recognized by all programs in special forms and write data into files
Iv. Modules
Send