Week 5 practice part4 --- Re module

hashlib module

Used for encryption-related operations, 3.x replaced the md5 module and the sha module, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithms

import hashlib
m = hashlib.md5()
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
m.update(b"It's been a long time since last time we ...")
 
print(m.digest()) #binary format hash
print(len(m.hexdigest())) #hexadecimal format hash
'''
def digest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of binary data. """
    pass
 
def hexdigest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of hexadecimal digits. """
    pass
 
'''
import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha1 ########
 
hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())

 

logging module

Many programs have the need to record logs, and the information contained in the log is the normal program access log, and may also output information such as errors and warnings. Python's logging module provides a standard log interface, through which you can store various logs. There are different formats of logs. The logged logs can be divided into 5 levels: debug(), info(), warning(), error() and critical(). Let's see how to use them.

最简单用法
import logging

logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")

#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down

Take a look at what these log levels mean

If you want to write the log to a file, it is also very simple

import logging
 
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

The level=loggin.INFO in the following sentence means that the logging level is set to INFO, that is, only logs with INFO or higher levels than the log will be recorded in the file. In this example , The first log will not be recorded. If you want to record the debug log, just change the log level to DEBUG.

logging.basicConfig(filename='example.log',level=logging.INFO)


I feel that the above log format forgot to add the time, the log does not know how to do it, so let's add it below!

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

#输出
12/12/2010 11:46:36 AM is when this event was logged.

 

Re module

The common regular expression symbol
'.' matches any character except \n by default. If flag DOTALL is specified, it matches any character, including newline
'^' at the beginning of the matching character. If flags MULTILINE is specified, this can also match (r"^a","\nabc\neee",flags=re.MULTILINE)
'$' matches end of character, or e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE). group() can also
'*' match the character before the * sign 0 or more times, re.findall("ab*", "cabb3abcbbac") The result is ['abb', 'ab', 'a']
'+ ' Match the previous character 1 or more times, re.findall("ab+","ab+cd+abb+bba") result ['ab', 'abb']
'?' Match the previous character 1 time or 0 times
'{m}' matches the previous character m times
'{n,m}' matches the previous character n to m times, re.findall("ab{1,3}","abb abc abbcbbb") result 'abb ', 'ab', 'abb']
'|' matches |left or |right characters, re.search("abc|ABC","ABCBabcCD").group() result 'ABC'
'(...)' group matching, re.search("(abc){2}a(123|456)c", "abcabca456c").group() result abcabca456c


'\A' only matches from the beginning of the character, re.search("\Aabc","alexabc") is the unmatched
'\Z' matches the end of the character, same as $
'\d' matches numbers 0-9
'\D' matches non-digits
'\w' matches [A-Za-z0-9]
'\W' matches non-[A-Za-z0-9]
's' matches whitespace, \t, \n, \ r , re.search("\s+","ab\tc1\n3").group() result '\t'
'(?P<name>...)' group matching re.search("(?P <province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict ("city") result {'province': '3714', 'city': '81', 'birthday': '1993'}

 

The most common matching syntax

re.match matches from the beginning
re.search matches contains
re.findall puts all matched characters into elements in a list and returns
re.splitall to match characters as list separators
re.sub matches characters and replaces

 

import re

print ( " *********** Usage of re.match *********** " )

# re.match starts with what 
res = re.match( " L " , " Lief " )
 print (res.group())

# \d matches a number 
res2 = re.match( " Lief\d " , " Lief123 " )
 print (res2.group())

# \d matches multiple numbers after 
res3 = re.match( " Lief\d+ " , " Lief123 " )
 print (res3.group())

print ( " *********** . Usage *********** " )

# . for one character, .+ for multiple characters (all) 
res4 = re.match( " .+ " , " Lief123 " )
 print (res4.group())

#match the first digit and all characters before it 
res5 = re.match( " .+\d " , " Lief123 " )
 print (res5.group())

print ( " *********** Usage of re.search *********** " )


res6 = re.search("e+\d", "LiefLee123")
print(res6.group())


res7 = re.search("L.+e", "Lief_Lee123")
print(res7.group())

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325327042&siteId=291194637