Summary of the modules commonly used in Python

Source: Internet
Author: User
Tags month name random shuffle shuffle python script

1. Modules and Packages

A. Definition:

Modules are used to logically organize Python code (variables, functions, classes, logic: Implementing a function), which is essentially a Python file at the end of the. Py. (Example: File name: test.py, corresponding module name: TEST)

Package: Used to logically organize a module, the essence is a directory (must have a __init__.py file)

b Import method

Import Module_name

Import Module_1 The essence of: is to explain the module_1 again

Which is to copy all the code in the Module_1 to Module_1.

From MODULE_NAME1 import name

The essence is to put the name variable in the module_name1 in the current program and run it again.

So you can print out the value of the name variable when you call it directly.

code example: Write your own module, other program calls, as follows:

Module module_1.py Code:

1 name = "Dean" 2 Def Say_hello (): 3 print ("Hello%s"%name)

The Python program that invokes the module main code is as follows: (Remember to call the module only when the import module name does not need to add. py)

Import Module_1

#调用变量

Print (Module_1.name)

#调用模块中的方法

Module_1.say_hello ()

The result after running the main program is as follows:

1 D:\python35\python.exe d:/python training/s14/day5/module_test/main.py2 dean3 Hello Dean4 5 Process finished with exit code 0

Import module_name1,module_name2

From module_name Import * (this method is not recommended)

From module_name import Logger as log (method of alias)

C. The essence of the import module is to interpret the Python file again

Import module_name---->module_name.py path---->sys.path----the >module_name.py

The essence of the import package is to execute the __init__.py under the package

A code example of importing a package:

Create a new Package_test package and create a test1.py Python program under the package to create a p_test.py program in the package's sibling directory

The code for TEST1 is as follows:

1 def Test (): 2     print ("int the Test1")

The code for __init__.py under the Package_test package is as follows:

1 #import test1 (theoretically this is possible but under Pycharm the test must use the following from. Import Test1) 2 from. Import  test13 print ("in the Init")

The code for P_test is as follows:

1 Import package_test   #执行__init__. Py2 package_test.test1.test ()

The result of running p_test in this way:

1 D:\python35\python.exe D:/python Training/s14/day5/p_test.py2 in the INIT3 int. the TEST14 5 Process finished with exit code 0

As can be seen from the above example, when importing a package is actually the __init__.py program under the package, so if you want to call the Python program below the package, you need to import the package under __init__.py.

2, the classification of the module

A Standard library

b Open source Module

C Automatically with module

3. Time Module

Time and DateTime

A common time representation method in Python:

A. Time stamp

Timestamp: The total number of times (in seconds) from January 1, 1970 00:00:00 until now

>>> Time.time ()

1472016249.393169

>>>

B. Formatted time string

C. Struct_time (tuple)

The relationship between the conversions is as follows:

1) time.localtime () converts a timestamp to a tuple of the current time

>>> Time.localtime ()

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=13, tm_min=27, tm_sec=55, tm_wday=2, tm_yday=237, tm_ isdst=0)

>>>

2) Time.gmtime () converts a timestamp to a tuple of the current time UTC time

>>> Time.gmtime ()

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=5, tm_min=35, tm_sec=43, tm_wday=2, tm_yday=237, TM_ISDST =0)

>>>

3) Time.mktime () can convert Struct_time to timestamp

>>> x = Time.localtime ()

>>> x

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=13, tm_min=39, tm_sec=42, tm_wday=2, tm_yday=237, tm_ isdst=0)

>>> time.mktime (x)

1472017182.0

>>>

4) Replace the struct_time with a formatted time string

>>> x

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=13, tm_min=39, tm_sec=42, tm_wday=2, tm_yday=237, tm_ isdst=0)

>>> time.strftime ("%y-%m-%d%h:%m:%s", x)

' 2016-08-24 13:39:42 '

>>>

5) You can convert a formatted time string to Struct_time

>>> time.strptime ("2016-08-24 14:05:32", "%y-%m-%d%h:%m:%s")

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=14, tm_min=5, tm_sec=32, tm_wday=2, tm_yday=237, TM_ISDST =-1)

>>>

6) Convert Struct_time to wed 24 14:22:47 2016 this format

>>> x

Time.struct_time (tm_year=2016, tm_mon=8, tm_mday=24, tm_hour=14, tm_min=22, tm_sec=47, tm_wday=2, tm_yday=237, tm_ isdst=0)

>>> time.asctime (x)

' Wed 24 14:22:47 2016 '

>>>

7) Replace the timestamp with Wed 24 14:22:47 2016 format

>>> x = Time.time ()

>>> x

1472019984.958831

>>> time.ctime (x)

' Wed 24 14:26:24 2016 '

>>>

1%a    Local (locale) simplified week name     2%a    Local full week name     3%b    Local simplified month name     4%b    local full month name     5%c    The local corresponding date and time represents the day ordinal of     6%d    one months (01-31)     7%H    hours (24-hour system, 00-23)     8%I hours    (12-hour system, 01-     9%j    the day of the Year (001-366)    %m    Month (01-12)    %m    minutes (00-59)    %p    Local AM or PM corresponding characters of      %s    seconds (01-61) for the       number of    weeks in a year. (00-53 weeks is the beginning of one weeks.) All days before the first Sunday are placed in the No. 0 week. The    first day of the%w one week (0-6,0 is Sunday)     %w    and%u are basically the same, unlike%w, which began in Monday for one weeks. +    %x    Local corresponding date    local corresponding    time    %y    Remove Century (00-99) year    %y    full year    %Z    the name of the time zone (if it does not exist as a null character), the    percent '% ' character

Datetime

Current time: Datetime.datetime.now ()

1. Random Module

Random.randint (1,3) can be removed at random 1-3

Random.randrange (1,3) randomly from within the range

The arguments passed by Random.choice () are sequences including list of strings, etc.

>>> random.choice ("Hello")

L

>>> random.choice ("Hello")

' O '

>>> random.choice ("Hello")

E

>>>

>>> Random.choice (["I", "Love", "You"])

I

>>> Random.choice (["I", "Love", "You"])

You

>>> Random.choice (["I", "Love", "You"])

You

>>> Random.choice (["I", "Love", "You"])

Love

>>>

Random.sample () randomly removes two bits from the preceding sequence

>>> random.sample ("Hello", 2)

[' l ', ' O ']

>>> random.sample ("Hello", 2)

[' H ', ' l ']

>>> random.sample ("Hello", 2)

[' H ', ' O ']

>>>

Random Shuffle Function:

>>> a=[1,2,3,4,5,6,7,8,9]

>>> Random.shuffle (a)

>>> A

[6, 3, 7, 4, 1, 8, 9, 2, 5]

>>>

Examples of generating random verification codes:

1 Import String 2 import random 3 A = "". Join (Random.sample (string.ascii_lowercase,4)) 4 print (a) 5 B = "". Join (Random.sam PLE (string.ascii_lowercase+string.digits,5)) 6 print (b) 7  8 c = "". Join (Random.sample (string.ascii_uppercase+ string.digits+string.ascii_lowercase,4)) 9 print (c) Ten d = "". Join (Random.sample (String.ascii_letters+string.digits, 4) print (d)

The results of the operation are as follows:

1 D:\python35\python.exe D:/python Training/s14/day5/Verification Code 2.py2 tbdy3 6te4b4 z2ua5 v8he6 7 Process finished with exit code 0

5. OS Module

 1 os.getcwd () Gets the current working directory, which is the directory path of the current Python script work 2 os.chdir ("DirName") changes the current script working directory, equivalent to the shell under CD 3 Os.curdir returns the current directory: ('. ') 4 OS.P Ardir Gets the parent directory string name of the current directory: (' ... ') 5 os.makedirs ('. ') can generate a multi-level recursive directory 6 os.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to The first level of the directory, if also empty, then delete, and so on 7 os.mkdir (' dirname ') to generate a single-level directory, equivalent to the shell mkdir dirname 8 os.rmdir (' dirname ') delete a single-level empty directory, if the directory is not empty can not be deleted, reported The equivalent of the shell rmdir dirname 9 os.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints a list of os.remove () deletes a file Os.rename ("O Ldname "," newname ") Rename File/directory Os.stat (' path/filename ') get File/directory information OS.SEP output operating system-specific path delimiter, win under" \ \ ", Linux under"/"OS.L INESEP output The line terminator used by the current platform, win under "\t\n", Linux under "\ n" os.pathsep output the string that is used to split the file path the Os.name output string indicates the current usage platform. Win-> ' NT ';  Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays the Os.environ acquisition system environment variable Os.path.abspath (PATH) Returns path normalized absolute path Os.path.split (path) divides path into directory and file name two tuples return Os.path.dirname (path) to the directory where path is returned. In fact, the first element of Os.path.split (path), Os.path.basename, returns the last file name of path.If path ends with a/or \, then a null value is returned.  The second element of Os.path.split (path) os.path.exists (path) returns true if path exists, or False24 os.path.isabs (path) If path does not exist If path is an absolute path, return True25 os.path.isfile (path) If path is an existing file, return true. Otherwise, return False26 Os.path.isdir (path) True if path is a directory that exists.  Otherwise return False27 Os.path.join (path1[, path2[, ...])  When multiple paths are combined and returned, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the last modified time of the file or directory to which path is pointing

6. SYS module

1 sys.argv           command line argument list, the first element is the program itself path 2 sys.exit (n)        exit the program, exit gracefully (0) 3 sys.version        get version information for Python interpreter 4 Sys.path           Returns the search path of the module, initializes with the value of the PYTHONPATH environment variable 5 sys.platform       returns the operating system platform name 6 Sys.stdout.write (' please: ')

7. Shutil Module

1 Import shutil2 3 A = open ("A.txt", "R", encoding= "Utf-8") 4 B = Open ("B.txt", "W", encoding= "Utf-8") 5 6 Shutil.copyfileobj (a , b)

Run enough to copy a file B to copy the contents of the a file into the B file

Shutil.copyfile ("B.txt", "C.txt") direct copy B.txt to C.txt

Shutil.copymode (SRC,DST) copies only permissions. Content, group, user are not changed

Shutil.copystat (SRC,DST) Copy status information

Shutil.copytree (src,dst,symlinks=false,ignore=none) recursive copy file

Shutil.rmtree (Path[,ignore_errors[,onerror])

Shutil.move (SR,DST)

Move files recursively

8. Two modules for serialization Json&pickle

JSON, used to convert between string and Python data types

Pickle for conversion between Python-specific types and Python data types

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

9, about shelve module

code example:

1 #AUTHOR: FAN 2 Import shelve 3 import datetime 4  5 D = shelve.open ("Shelve_test") 6  7 info = {"Name": "Dean", "job" : "It", "age": 8  9 d["name"]=info["name"]10 d["job"]=info["job"]11 d["date"]=datetime.datetime.now () d.close ()

Running the result, the following three files are generated

The code for removing the stored data is as follows:

1 d = shelve.open ("Shelve_test") 2 print (D.get ("name")) 3 print (D.get ("Job")) 4 print (D.get ("date"))

The results of the operation are as follows:

1 D:\python35\python.exe D:/python Training/s14/day5/shelve module/shelve_test.py2 dean3 it4 2016-08-24 16:04:13.3254825 6 Process Finished with exit code 0

10. Regular RE Module

1 '. '     The default match is any character except \ n, if you specify flag Dotall, match any character, including the line 2 ' ^ '     match character beginning, if you specify flags MULTILINE, this can also match (r "^a", "\nabc\neee", flags =re. MULTILINE) 3 ' $ '     matches the end of the character, or E.search ("foo$", "BFOO\NSDFSF", Flags=re. MULTILINE). Group () can also 4 ' * '     matches the character before the * number 0 or more times, Re.findall ("ab*", "Cabb3abcbbac")  results for [' ABB ', ' ab ', ' a '] 5 ' + '     Match previous character 1 or more times, Re.findall ("ab+", "Ab+cd+abb+bba") result [' AB ', ' ABB '] 6 '? '     Match the previous character 1 or 0 times 7 ' {m} '   matches the previous character m times 8 ' {n,m} ' matches the previous character N to M times, Re.findall ("ab{1,3}", "ABB ABC abbcbbb") Results ' ABB ', ' AB ', ' ABB '] 9 ' | '     Match | left or | Right character, re.search ("abc| ABC "," ABCBABCCD "). Group () Results ' ABC ' 10 ' (...) ' Grouping matches, Re.search (" (ABC) {2}a (123|456) C "," abcabca456c "). Group () results Abcabca456c11  '  \a '    only matches from the beginning of the character, Re.search ("\aabc", "ALEXABC") is not matched to the end of the ' \z '    match character, with the $ ' \d ' Match    number 0-916 ' \d ' matches    non-digit ' \w '    match [a-za-z0-9]18 ' \w ' matches    non-[a-za-z0-9]19 ' s ' matching     whitespace characters, \ t, \ n, \ r, Re.search ("\s+", "Ab\tc1\n3"). Group () result ' \ t '

R represents the meaning of canceling special characters inside quotes

The most common matching syntax:

Re.match match from the beginning

Re.search Match contains

Re.findall all matching characters to the elements in the list to return

Re.splitall as a list separator with matched characters

Re.sub match characters and replace

Here is an example of a regular that helps to understand:

  1 >>> re.match ("^zhao", "zhaofan123") 2 <_sre. Sre_match object; Span= (0, 4), match= ' Zhao ' > 3 >>> re.match ("^ww", "zhaofan123") 4 >>> 5 It can also be seen from here that if there is a return there is a match, otherwise there is no Match to 6 >>> res = Re.match ("^zhao", "zhaofan123") 7 >>> Res 8 <_sre. Sre_match object; Span= (0, 4), match= ' Zhao ' > 9 >>> res.group () #如果想要查看匹配的内容. Group () ' Zhao ' >>> 12 matches Zhao back and the number 1  3 >>> res = Re.match ("^zhao\d", "zhao2323fan123") + >>> Res.group () ' Zhao2 ' 16 matches multiple digits >>> res = Re.match ("^zhao\d+", "zhao2323fan123") >>> res.group () ' zhao2323 ' >>> 21 22 Find specific characters @ &G T;>> re.search ("F.+n", "zhao2323fan123") <_sre. Sre_match object; Span= (8, one), match= ' fan ' > >>> >>> re.search ("F.+n", "zhao2323fan123n") <_sre. Sre_match object; Span= (8), match= ' fan123n ' > >>> re.search ("F[a-z]+n", "zhao2323fan123n") <_sre . SRe_match object; Span= (8, one), match= ' fan ' > >>> 33 $ is the last match to the string >>> re.search ("#.+#", "1234#hello#") and <_sre. Sre_match object; Span= (4, one), match= ' #hello # > >>> PNS >>> re.search ("AA?", "Zhaaaofan") <_sre. Sre_match object; Span= (2, 4), match= ' AA ' > >>> re.search ("AAA?", "Zhaaaofan") <_sre. Sre_match object; Span= (2, 5), match= ' aaa ' > >>> re.search ("AAA", "Zhaaofan") <_sre. Sre_match object; Span= (2, 4), match= ' AA ' > >>> <_sre. Sre_match object; Span= (2, 5), match= ' aaa ' > >>> re.search ("AAA", "Zhaaofaaan") <_sre. Sre_match object; Span= (2, 4), match= ' AA ' > >>> re.search ("AAA", "Zhaofaaan") <_sre. Sre_match object; Span= (5, 8), match= ' aaa ' > Wuyi >>> re.search ("AAA", "Zhaaofaaan") <_sre. Sre_match object; Span= (2, 4), match= ' AA ' > 53 can be well understood from above? Matches the previous character 0 or 1 times 54 popular say is AA behind there are 1 or no a can match to the >>>Re.search ("[0-9]{3}", "aaax234sdfaass22s") <_sre. Sre_match object; Span= (4, 7), match= ' 234 ' > >>> 58 matching numbers 3 times >>> re.search ("[0-9]{3}", "aaax234sdfaass22s") <_ Sre. Sre_match object; Span= (4, 7), match= ' 234 ' > >>> 62 matching numbers 1 times to 3 times Re.search ("[0-9]{1,3}", "AAA23SDFSDF2323SS") 64 <_sre. Sre_match object; Span= (3, 5), match= ' ' > 2 >>> 66 Find all the digital Re.findall ("[0-9]{1,3}", "SSS23SDF2223SS11") 68 3 ', ' 222 ', ' 3 ', ' one '] >>> >>> re.search ("abc| ABC "," ABCABCD "). Group ()" ABC ">>> Re.findall (" abc| ABC "," ABCABCCD ") [' abc ', ' abc '] >>> <_sre >>> re.search (" abc{2} "," ZHAOFANABCCC "). Sre_match object; Span= (7, one), match= ' ABCC ' > >>> + >>> re.search ("(ABC) {2}", "Zhaofanabcabc") <_sre. Sre_match object; Span= (7, +), match= ' ABCABC ' > 81 Advanced Usage: re.search (? p<id>[0-9]+) "," Abc12345daf#s22 ") &LT;_sre. Sre_match object; Span= (3, 8), match= ' 12345 ' > >>> re.search (? p<id>[0-9]+) "," Abc12345daf#s22 "). Group () 12345 ' >>> re.search (?  p<id>[0-9]+) "," Abc12345daf#s22 "). Groupdict (): {' id ': ' 12345 '} >>> the use of the £ º >>> Re.split ("[0-9]+", "ACB23SDF2D22SS"), [' ACB ', ' SDF ', ' d ', ' SS '] 94 >>> The use of the sub replacement of the Re.sub ("[0-9 ]+ "," # "," 234ssdfsdf23sdf22ss3s ")" #ssdfsdf #sdf#ss#s ' 98 >>> ("[Re.sub", "#", " 234ssdfsdf23sdf22ss3s ", count=2) 101 ' #ssdfsdf #sdf22ss3s ' 102 >>>

Summary of the modules commonly used in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.