NO.5: The Way to Learn python by Yourself - Standard Library, Regular Expressions

Keywords: Python Programming encoding Linux

Introduction

How time flies! At last, I have finished my CET-6, and I have to catch up with my progress in Python study. Okay, start the week.

text

Modular

The essence of module is the file at the end of'.py'. It can be used to organize Python code logically. It can be variables, functions, classes or logic, mainly to achieve a function. If the file name is a module named'test.py', then its module name is'test'. Modules are different from packages. Packages are used to organize files logically. The essence of packages is a directory, but they must have a file named _init_ py. Module import method, example.

import test

import

import a module, in fact, is to interpret all the code in the module file and assign it to the module name. It can be combined with from, examples.

from test import function

The combined function is actually to take out the function part of'test.py'and execute it. The essence of the import module is to interpret a Python file (under the sys.path search path). The essence of importing a package is to interpret the'_init_ py'file in the package directory.

Note that in the'_init_ py'file under the package, import cannot be imported directly into the module within the package. Correct import method, example.

#__init__.py
from . import test#Import from absolute path

#main.py
import package
package.test()#call

classification

Modules are mainly divided into three categories: standard library, open source module and custom module.

Standard libraries are libraries provided by Python for programmers and can be directly imported and invoked. Such as os,sys, etc.

Open source module is an open source Python module developed by developers, which can be downloaded and installed from the network. Such as numpy,pandas, etc.

Custom modules are self-programming modules.

Some common standard libraries are described in detail below.

time

There are three main formats of time: struc_time format, timestamp format and fixed format format.

import time
time.localtime()#UTC National standard time, struct_time format
time.timezone#Difference with standard time, timestamp format, unit s
time.daylight#Whether to use daylight saving time or not
time.sleep()#Stop for a few seconds.
time.gmtime()#Time stamp conversion to struct_time Formatted UTC time
time.localtime()#Time stamp conversion to struct_time Current time zone time of format(UTC+8)
time.mktime()#struct_time Format conversion to timestamp
time.strftime('%Y-%m-%d %H:%M:%S',x)%take struct_time Convert to formatted string time
time.strptime('2018-11-1 5:21:10','%Y-%m-%d %H:%M:%S')#Convert formatting time to struct_time format
time.asctime()#current time(default)Or structured tuple time conversion to English display
time.ctime()#current time(default)Or time stamp conversion to English display

datatime

import datetime
datetime.datetime.now()#Current date and time
datetime.datetime.now()-datetime.timedelta(3)#The default is sky.
datetime.datetime.now()-datetime.timedelta(hours=3)#3 Hours ago

random

import random
random.random()#random[0~1)Floating Points Between
random.randint(1,10)#[1~10]Random integers between
random.randrange(1,10)#[1~10)Random integers between
random.choice('hello word!')#Take a random value from it.
random.sample('hello word!',2)#Randomly take a given number from it
random.uniform(1,10)#[1~10]Random Floating Points Between
x = [1,2,3,4,5]
random.shuffle(x)#x Shuffle the cards

os

import os
os.getcwd()#Get the current directory
os.chdir(r'C:\user')#Transfer to other directories
os.curdir#current directory
os.pardir#Superior Catalogue
os.makedirs(r'C:\a\b\c')#Recursive creation of directories
os.removedirs(r'C:\a\b\c')#If null, recurse to the upper level and delete
os.mkdir(r'C:\a\b\c')#Create directories without recursion
os.rmdir(r'C:\a\b\c')#Delete directories without recursion
os.listdir('.')#All files in the current directory
os.remove()#Delete a file
os.rename('oldname','newname')#rename
os.stat(r'C:\a.jpg')#file information
os.sep#win The lower partitioner is\\ linux The lower partitioner is/
os.linesep#Terminator win The lower partitioner is\r\n linux The lower partitioner is\n
os.pathsep#Segmentation Symbols of Current Platform Path win;
os.name#Current system name
os.system()#Executive order
os.environ#Getting environmental variables
os.path.abspath()#Get an absolute path to a file
os.path.split()#Partition of folders and file names in paths
os.path.dirname()#Divide folders and file names in paths into directory names
os.path.basename()#The file name of the folder and file name split in the path
os.path.exists()#Judging whether a path exists
os.path.isabs()#Is it an absolute path?
os.path.isfile()#Determine whether it is a document or not
os.path.isdir()#Determine whether it is a catalog
os.path.join(r'C:',r'\a')#Combining multiple paths back
os.path.getatime()#Get the last access time of the file
os.path.getmtime()#Get the last modification time of the file

sys

import sys
sys.argv#Command line parameters list
sys.exit(n)#Exit procedure, 0
sys.version#python Version information
sys.path#Search path
sys.platform#Operating System Platform Name
sys.stdout.write('please:')#Can be used to write progress bars

shutil

 

import shutil#File, folder, compressed package processing
shutil.copyfileobj(Source file object,Target file object[,length])
f1,f2 = open('test1',encoding='utf-8'),open('test2','w',encoding='utf-8')
shutil.copyfileobj(f1,f2)
shutil.copyfile('test1','test2')
shutil.copystat('test1','test2')#Copy file status and permissions
shutil.copy('test1','test2')#Copy files and permissions
shutil.copy2('test1','test2')#Copy files and status
shutil.copytree('test1','test2')#Recursive copy, copy all files in the directory
shutil.rmtree('test2')#Delete all files in the directory recursively
shutil.move('test1','test2')#Recursive Mobile Files
shutil.make_archive('Compressed package file name or path','Compressed Packet Type zip,tar')

 

zipfile/tarfile

 

import zipfile
z = zipfile.ZipFile('test.zip','w')
z.write('test1.py')
z.close()
z = zipfile.ZipFile('test.zip','r')
z.extractall()
z.close()

shelve

import shelve#Memory Data Persistence Module
d = shelve.open('test')
class test(object):
    def __init__(self,n):
        self.n = n
t = test(123)
t2 = test(1233)
name = ['aa','bb','cc']
d['test'] = name #Persistence List
d['t1'] = t #Persistence class
d['t2'] = t2
d.close()
d = shelve.open('test')#open shelve
d.get('t1')#read out t1

configparser

 

import configparser#Configuration document
#generate
config = configparser.ConfigParser()
config['DEFAULT'] = {'LALAL':'23','AAFF':'22'
}
config['NEW'] = {}
with open('test.ini','w') as configfile:
   config.write(configfile)
#read
config = configparser.ConfigParser()
config.read('test.ini')
config.sections()#Print node
config['new']['lala']
#delete
sec = conf.remove_section('NEW')
conf.write(open('test.ini','w'))

 

hashlib

 

import hashlib#hashlib For encryption, md5
m = hashlib.md5()
m.update(b'hello')
m.update(b'new')
print(m.hexdigest())#sha1\sha512\sha256....

 

hmac

 

import hmac
h = hmac.new(b'key','information'.encode(encoding=utf-8))
print(h.digest())
print(h.hexdigest())

 

Regular expression re

 

import re
#Matching rules:
#'.'Matching elimination'\n'Any character other than that specified flag DOTALL It can match any character.
#'^'Match the beginning of the character, specify flag MULTLTNE,Can match('a','\nabc\neee',flag=re.MULTILINE)
#'$'Match End
#'*'matching*The previous character is zero or more times, re.findall('ab*','cabb3abcbaac')
#'+'Match the previous character one or more times
#'?'Match the previous character 1 or 0 times
#'{m}'Match the previous character m second
#'{n,m}'Match the previous character n reach m second
#'|'matching'|'Left or right characters
#'(...)'Packet matching
#'\A'Match only from the beginning of the character
#'\Z'Match character endings
#'\d'Matching number 0~9
#'\D'Matching non-numerals
#'\w'matching[A-Za-z0-9]
#'\w'Matching non[A-Za-z0-9]
#'\s'Match blank characters,\t,\n,\r
re.search()#Global search, retrieve one and return
re.match()#Search from scratch, retrieve one and return
re.findall()#Remove all and return
re.split()#Division
re.sub()#replace

 

task

Python string calculator

Functions:

1. Input string, calculation

2. Parentheses, multiplication and division, priority

#-*- coding:utf-8 -*-
#author: Kai Zhang
#string calculation

import re

def mul(factor_1,factor_2):
    '''multiplication'''
    value = float(factor_1) * float(factor_2)
    return str(value)

def div(factor_1,factor_2):
    '''division'''
    value = float(factor_1) / float(factor_2)
    return str(value)

def add(factor_1,factor_2):
    '''addition'''
    value = float(factor_1) + float(factor_2)
    return str(value)

def sub(factor_1,factor_2):
    '''subtraction'''
    value = float(factor_1) - float(factor_2)
    return str(value)

def muldiv(formula):
    '''Calculate all multiplications and divisions'''
    formula = formula.replace('/*','/')
    formula = formula.replace('*/','/')
    muldiv_flag = True
    while muldiv_flag:
        inside = re.search('\d+\.?\d*[\*\/]-?\d+\.?\d*',formula)
        if inside:
            inside = inside.group()
            number = re.findall('\d+\.?\d*',inside)
            if '-' in inside:
                number[1] = '-' + number[1]
            if '*' in inside:
                value = mul(number[0],number[1])
            else:
                value = div(number[0],number[1])
            formula = formula.replace(inside,value)
        else:
            muldiv_flag = False
    return formula

def addsub(formula):
    '''Calculate all additions and subtractions'''
    formula = formula.replace('--','+')
    formula = formula.replace('-+','-')
    formula = formula.replace('+-','-')
    formula = formula.replace('++','+')
    if formula[0] == '-':
        formula = '0'+formula
    addsub_flag = True
    while addsub_flag:
        inside = re.search('\d+\.?\d*[\+\-]\d+\.?\d*',formula)
        if inside:
            inside = inside.group()
            print(inside)
            number = re.findall('\d+\.?\d*',inside)
            if '+' in inside:
                value = add(number[0],number[1])
            else:
                value = sub(number[0],number[1])
            formula = formula.replace(inside,value)
            print(value)
        else:
            addsub_flag = False
    return formula

def calculat(formula):
    '''Open brackets'''
    bracket_flag = True
    result = 0
    while bracket_flag:
        inside = re.search('\([\d\.\+\-\*\/]*\)',formula)
        if inside:
            inside = inside.group()
            value = muldiv(inside.strip('()'))#Calculate multiplication and division after removing left and right brackets
            value = addsub(value)#Calculation addition and subtraction
            formula = formula.replace(inside,value)
        else:
            bracket_flag = False
    value = muldiv(formula)
    result = addsub(value)#Calculation addition and subtraction
    return float(result)

if __name__ == '__main__':
    formula = input('Please enter the formula to be calculated.>>')
    formula = re.sub('\s','',formula)#Remove spaces
    print('>>%f'%(eval(formula)))#Show the right results
    result = calculat(formula)#Computational programming results
    print('>>%f'%(result))#Show the results of programming

Posted by gitosh on Tue, 14 May 2019 08:32:42 -0700