python module knowledge three hashlib encryption module, collections, re module

8.hashlib encryption module

Mainly used for encryption and checksum

Common ciphertext: md5, sha1, sha256, sha512

  1. Same as long as the plaintext, the ciphertext to the same
  2. They are not the same as long as the plaintext, the ciphertext is not identical
  3. Not of inverse (can not be decrypted) - md5 China cracked

The most commonly used is the MD5 (for verification), encryption usually use sha1

'''加密
    1.指定要加密的方式
    2.将要加密的内容转成字节
    3.合成
'''
import hashlib
md5 = hashlib.md5()#1
md5 = hashlib.sha1()
md5 = hashlib.sha256()
md5 = hashlib.sha512()

md5.update("alex123".encode("utf-8"))#2  密文与编码方式无关,只与加密方式和明文有关
print(md5.hexdigest())#3

With salt:

#1.固定加盐
import hashlib
pwd = "wang123"
md5 = hashlib.md5("我去".encode("utf-8"))
md5 = hashlib.md5(b"alex07yu")
md5.update(pwd.encode("utf-8"))
print(md5.hexdigest())


#2.动态加盐
user = input("username:")
pwd = input("passwd:")
md5 = hashlib.md5(user.encode("utf-8"))
md5.update(pwd.encode("utf-8"))
print(md5.hexigest())

#3.读取文件内容加密
f = open(r"F:\s24\day17\python-3.6.6-amd64.exe",'rb')
md5 = hashlib.md5()
md5.update(f.read())
print(md5.hexdigest())

#4.逐步加密和一次加密结果一样
import hashlib
pwd1 = 'a'
pwd2 = 'b'
pwd3 = 'ab'
md5 = hashlib.md5()
md5.update(pwd1.encode("utf-8"))
md5.update(pwd2.encode("utf-8"))
print(md5.hexdigest())
md6 = hashlib.md5()
md6.update(pwd3.encode("utf-8"))

#5.接3,当文件太大时,逐步加密,节省内存
import hashlib
f = open(f"F:\s24\day17\python-3.6.6-amd64.exe",'rb')
md5 = hashlib.md5()
while 1:
    msg = f.read(1024)#每次读取1024字节
    if msg:
        md5.update(msg)
    else:
        print(md5.hexdigest())
        break

9.collections

  1. namedtuple: Named tuples. The name of generated that can be used to access the content of the element tuple
  2. deque: deque can be quickly added to the other side and delete objects
  3. Counter: a counter for calculating the number of repetitive elements
  4. defaultdict: Dictionary with default values
  5. OrdereDict
from collections import namedtuple
#1.
point = namedtuple('a',['x','y'])
p = point(1,2)
print(p)
#2.
from collections import deque
lst1 = depue([1,2,3,4,5])
lst1.append(8)
lst1.appendleft(0)
lst1.pop()
lst1.popleft()
print(lst1[4])
#3.***
from collections import Counter
s1 = '13215af13213a1dfa3sdfa3'
print(dict(Count(s1)))
s2 = [1,1,2,2,3,3]
print(dict(Count(s2)))
s3 = (1,2,3,3,4,5,6,7,78)
print(dict(Count(s3)))
#4.
from collections import defaultdict
dic = defaultdict(list)
dic['k1'].append(1)
print(dic)
#结果:defaultdict(<class 'list'>, {'k1': [1]})
'''
将列表中大于66的放到k1中,其余的放到k2中,用带有默认值的字典模块做
'''
li = [11,22,33,44,55,77,88,99,90]
from collections import defaultdict
dic = defaultdict(set)
for i in li:
    if i > 60:
        dic['k1'].add(i)
    else:
        dic['k2'].add(i)
print(dic)
#5.了解

10.re module

Regular: it is a combination of some symbols that have special meaning or the method described character string together (referred to as regular expressions). Regular rule is used to describe a class of things

Metacharacters Matching rules
\w Match letter (containing Chinese), or numbers, or underscores
\W In addition to matching the letter (containing Chinese), numbers, or underscore
\s Matches any whitespace
\S Matches any non-whitespace
\d Match numbers, equivalent to [0-9]
\D Matching non-numeric
\A From the beginning of the string match
\WITH Matching string end, if it is for the line, only the matching results of the previous wrap
\n Matches a newline
\t A matching tab
^ Matches the beginning of the string
$ End of the string
. Matches any character except newline, when re.DOTALL flag is specified, will match any character including newline
[] Matching character set characters, [abc] represents a, b, c. [Az] z represents a single character to a '-' not matched, when placed before the beginning of the match -> [-az]
[^] In addition to the matching character set characters all characters, [^ abc] represents a single character or a non-b or c,
* Previous character 0 times or an unlimited number of extensions, abc * represents ab, abc, abcc, abccc ......
+ 1 previous character or unlimited expansion,
Previous character zero or one time extension
{n} A front extension character n times, ab {2} c represents abbc
{m,n} Character before a match extension extended to n times m, with n times, matching greedy
| Expression of a left or right, a | b matches a or b
() Matching expression in parentheses, represent a group, brackets available |, (abc | def) represents abc or def. m (? :) t outputted together inside and outside the brackets
1. Methods
  1. re.search (): In the search string to match the first position of regular expressions, and returns a math objects, .group () to view the object.

  2. re.match (): from the start position of the regular expression matching string, and returns the object match

    match object does not match the return None

import re
#search找到第一个就停止查找
print(re.search(r'[1-9]\d{3}','100086'))
print(re.search(r'[1-9]\d{3}','00086001500012').group())
#match只从开头找,开头不符合就不查找了
print(re.search(r'[1-9]\d{3}','100086'))
print(re.match(r'[1-9]\d{3}','00086002154'))
  1. re.findall (): a search string, to return a list of all other types of matching substring
  2. re.split (): according to the result of dividing a string matching the regular expression, returns a list of
  3. re.sub (): replace all regular expression matching substring in a string, the string returned alternative
import re
#分割
s = 'aa#所谓结案,2123:lkj!无*所谓'
print(re.split("[#,:!*]",s))

#替换
print(re.sub("所谓","me",s))
  1. re.finditer (): returns an iterator address
import re
f = re.finditer("\w","你是垃圾")
print(next(f).group())

for i in f:
    print(i)
2.re two equivalent methods:
  1. Functional Usage: one-time operation
  2. Object-oriented Usage: this operation can be compiled, re.compile () -> define matching rules
import
#1.函数式用法:
rst = re.search(r'[1-9]\d{5}','BIT 100086')
print(rst.group())
#2.面向对象:
pat = re.compile(r'[1-9]\d{5}')
rst = pst.serch('BIT 100086')
3. greed matching and regular minimum matching (matching default greedy)
symbol Matching rules Greed rules
*? Previous character 0 or unlimited expansion The minimum match
+? 1 or The minimum match
?? 0 or 1 The minimum match
{m,n} Before you extend a character mn times with n Greed match
import re
#贪婪匹配
match = re.search(r'py.*n','pyanbncndn')
print(match.group(0))
#最小匹配加'?'
match = re.search(r'py.*?n','pyanbncndn')
print(match.group(0))
4. a name

m (? <name> \ w +) t group ( "name")

import re
print(re.search("(?<ta_name>\w+)\w+",h1hellth).group("ta_name"))

Guess you like

Origin www.cnblogs.com/Onlywang/p/11285672.html