Python Learning Series (6) (module)

Source: Internet
Author: User
Tags valid email address

Python Learning Series (6) (module)

I. Basic Introduction of modules

1. import other standard modules

Standard Library: the module in the Python Standard installation package.

Several Methods for introducing modules:

I) import module: import moduleName

Ii) Introduce functions in the module: from moduleName import function1, function2 ,......

Iii) Introduce all functions in the module: from moduleName import *

How to use functions in the module:

ModuleName. function (agrs)

Example:

>>> import math>>> r=math.sqrt(16)>>> print r4.0

If the module or function name is too long, you can use as to give the module an alias after import, and then use the function in the module through "alias. function.

Example:

>>> import webbrowser as web>>> web.open_new_tab('http://www.cnblogs.com')True

2. Use a custom Module

Under testfile. py:

def readfile():    fr=open('wformat.txt','r')    while (1==1):        line=fr.readline()        if(line==''):            break        else:            print line    fr.close()

Under test. py: (in the same directory as testfile. py)

import testfiletestfile.readfile()

Result

>>> Name age sex Zhang San 78 male Li Si 50 male Wang Wu 80 male Zhang Qiang 90 female

Call hierarchy:


If the called Module Program and Module Program are not in the same directory file, you need to call OS. path. append (the directory where the module File is located)

Note :. pyc is a module bytecode file. When using the module as a Python interpreter, you need to load the module into the system. py ratio. new pyc, you need to re-compile and generate. pyc. Otherwise, no. File. pyc is completed when the module File is loaded for the first time.

3. Use the module sample Json Module

1) using the dumps function in Python, you can convert the Python data dictionary into a Json data structure.


Example:

import jsons=[{'f':(1,3,5,'a'),'x':None}]d=json.dumps(s)print d

Result

>>>[{"x": null, "f": [1, 3, 5, "a"]}]

2) convert Json data into Python data and decode loads (the corresponding relationship is shown in the table above)

Ii. RegEx Module

1) common applications of Regular Expressions:

  • Verification string: such as a valid email address or HTTP address.

  • Search for strings

  • Replace string

  • Extract string

    2) Basic concepts:

    Regular Expression: A piece of text or a formula used to describe formulas that match a type of string in a certain pattern, and the formula has a certain pattern.

    Match: for a given piece of text or string, use a regular expression to find the string that matches the regular expression from the text or string. It is possible that more than one part of the text or string meets the given regular expression, which is called a match for each of these parts.

    Metacharacters: Only one character or location can be matched at a time. Therefore, metacharacters: The metacharacters that match the characters and the metacharacters that match the positions.

    I) metacharacters matching characters

    • ^ String: Match all rows starting with a string

    • String $: Match all rows ending with a string

    • $ ^: Match empty rows

    • \ BStr: \ B matches the words starting with Str (equivalent to \ <)

    • Str \ B: \ B matches the words ending with Str (equivalent to \>)

      Ii) metacharacters matching locations

      • \ W: Match characters in a word (letters, numbers, and underscores)

      • \ W: Match non-characters in a word

      • \ D: Match numbers in words

      • \ D: Match non-numbers in words

      • \ S: Match space characters in a word

      • \ S: Match non-space characters in a word

        Example:

        >>> import re>>> s='Hello www.jeapedu.com'>>> res=r'\bjea'>>> print re.findall(res,s)['jea']>>> res=r'jea\b'>>> print re.findall(res,s)[]>>> res=r'edu\b'>>> print re.findall(res,s)['edu']import res='''ahellowww.baidu.comhello worldnice hellod worldpiece of helloe world'''res=r'\hello'print 'hello:',re.findall(res,s) >>> ================================ RESTART ================================>>>hello ['hello', 'hello', 'hello', 'hello']import res='a1b2c3d'res='\w\d'print re.findall(res,s)res='\w\d\w'print re.findall(res,s)>>> ================================ RESTART ================================>>>['a1', 'b2', 'c3']['a1b', 'c3d']

        Character Set: A Character Set enclosed by square brackets. If any of the characters is matched, the character set matches the character set. You can add ^ To the character set before the character set.

        Example:

        Import res = ''' Plz write a mail to zhangbocheng189@163.comor 649414754@qq.com, thanks! '''Res = R' \ w [\ w \. -] + @ [\ w \. -] + \. \ w {2, 4} '# * indicates that the match is zero or more times, and + indicates that the match is one or more times. Print re. findall (res, s) >>> ================================== RESTART ======== ======================================>> ['zhangbocheng189 @ 163.com ', '2017 @ qq.com ']

        Group or submode: divides all or part of a regular expression into one or more groups. The Characters Used for grouping are "(" and ")".

        Example:

        Import res = '''www .baidu.comwww.BaidU.comwww.bAIDU.comwww.baidu.comwww.Baidu.com '''res1 = R' (B | B) \ w * (u | U) '# * Indicates matching 0 times or more, + indicates matching once or more times. Res2 = R' [bB] \ w * (u | U) 'res3 = R' [bB] \ w * [uU] 'print res1 + ': 'print re. findall (res1, s) print res2 + ': 'print re. findall (res2, s) print res3 + ': 'print re. findall (res3, s) >>> ================================== RESTART ======== ==========================================>>> (B | B) \ w * (u | U): [('B', 'U '), ('B', 'U'), ('B', 'U')] [bB] \ w * (u | u): ['U ', 'U', 'U'] [bB] \ w * [uU]: ['baidu ', 'baidu', 'baidu']

        Qualifier: used to specify the number of times that a specific character or character set can appear repeatedly.

        • (Pattern )?: Repeated 0 or 1 times, equivalent to {0, 1}

        • (Pattern )*: At least 0 duplicates, equivalent to {0 ,}

        • (Pattern) +: Repeat at least 1 time, equivalent to {1 ,}

        • (Pattern) {m: n}: Repeated at least m times, at most m times

        • (Pattern )??: Use repeated 0 times or 1 time

        • (Pattern )*?: Use the first duplicate match as little as possible

        • (Pattern) +?: Use as few duplicates as possible but at least once

          Example:

          Import res = ''' Tell to me 110-123-1114119 or call 4008-6688-9988 or 13306247965 ''' res = R' \ d + \ D \ d + '# * Indicates matching 0 times or more, + indicates matching once or more times. Res1 = R' \ d {11} 'print re. findall (res, s) print re. findall (res1, s) >>> ================================== RESTART ======== ========================================>>> ['2017-123-1114119 ', '2017-6688-9988 '] ['20170901']

          Wildcard: matches a character string with a limited length. For example, a point number matches any character.

          Escape characters: (See:Python Learning Series (3) (string))

          3) Application Example:

          import res='hello www.baidu.com'print '----------------compile--------------------'res='[\s\.]'pat=re.compile(res)print pat.findall(s)print pat.split(s)print '----------------split--------------------'res='[\s\.]'print re.findall(res,s)print re.split(res,s) >>> ================================ RESTART ================================>>>----------------compile--------------------[' ', '.', '.']['hello', 'www', 'baidu', 'com']----------------split--------------------[' ', '.', '.']['hello', 'www', 'baidu', 'com']

          Iii. Summary

          This chapter mainly introduces the advanced knowledge of python development, modules and related knowledge of regular expressions. Regular Expressions are a very important knowledge point for programming and require more research.

          Additional tips:

          1. sys module: Contains functions related to the Python interpreter and its environment.

          Import sysfor I in sys. argv: print I >>> D: \ Python learning \ pythontest \ test. py

          2. dir function: listsIdentifierSuch as functions, classes, and variables. When a module name is provided for dir, the module definedName ListOtherwise, the list of names defined in the current module is returned.

          >>> Import sys >>> dir () ['_ builtins _', '_ doc _', '_ file __', '_ name _', '_ package _', 'I', 'sys '] >>> a = 5 >>> dir () ['_ builtins _', '_ doc _', '_ file _', '_ name __', '_ package _', 'A', 'I', 'sys '] >>> del a # delete a variable/name >>> dir () ['_ builtins _', '_ doc _', '_ file _', '_ name __', '_ package _', 'I', 'sys ']

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.