Python notes day19 (module) | collections, time, random, os, sys modules

1. Content review

# 正则表达式
# 字符组 [字符]
# 元字符
    # \w \d \s
    # \W \D \S
    # . 除了换行符以外的任意字符
    # \n \t
    # \b
    # ^ $ 匹配字符串的开始和结束
    # () 分组  是对多个字符组整体量词约束的时候用的
                #re模块:分组是有优先的
                    # findall
                    # split
    # | 从左到右匹配,只要匹配上就不继续匹配了。所以应该把长的放前面
    # [^] 除了字符组内的其他都匹配
# 量词
    # *   0~
    # +   1~
    # ?  0~1
    # {n} n
    # {n,} n~
    # {n,m} n~m
# 转义的问题
# import re
# re.findall(r'\\s',r'\s')

# 惰性匹配
# 量词后面加问号
    # .*?abc 一直取遇到abc就停

# re模块
# import re
# re.findall('\d','awir17948jsdc',re.S)
# 返回值:列表 列表中是所有匹配到的项

# ret = search('\d(\w)+','awir17948jsdc'# ret = search('\d(?P<name>\w)+','awir17948jsdc'# 找整个字符串,遇到匹配上的就返回,遇不到就None
# 如果有返回值ret.group()就可以取到值
# 取分组中的内容 : ret.group(1)   /  ret.group('name')

# match
# 从头开始匹配,匹配上了就返回,匹配不上就是None
# 如果匹配上了 .group取值

# 分割 split
# 替换 sub 和 subn
# finditer 返回迭代器
# compile 编译 :正则表达式很长且要多次使用

import re

# ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
# #还可以在分组中利用?<name>的形式给分组起名字
# #获取的匹配结果可以直接用group('名字')拿到对应的值
# print(ret.group('tag_name'))   #结果 :h1
# print(ret.group())             #结果 :<h1>hello</h1>

# ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
# #如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致
# #获取的匹配结果可以直接用group(序号)拿到对应的值
# print(ret.group(1))
# print(ret.group())  #结果 :<h1>hello</h1>

import re

# ret=re.findall(r"\d+\.\d+|(\d+)","1-2*(60+(-40.35/5)-(-4*3))")
# print(ret) #['1', '2', '60', '40', '35', '5', '4', '3']
# ret.remove('')
# print(ret)
# ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
# print(ret) #['1', '-2', '60', '', '5', '-4', '3']
# ret.remove("")
# print(ret) #['1', '-2', '60', '5', '-4', '3']

2, collections module

This module encapsulates the above data structure and adds some cool data structures, such as:

1) Counter: Counter, used to count the number of elements

2) OrderDict: ordered dictionary

3) defaultdict: a dictionary with a value with a default type

4) namedtuple: named tuple, access tuple elements by name

5) deque: two-way queue, both the head and tail of the queue can be put and taken (compared with one-way queue, one-way queue can only be put at one end and taken at the other end)

# from collections import namedtuple
# Point = namedtuple('point',['x','y','z'])
# p1 = Point(1,2,3)
# p2 = Point(3,2,1)
# print(p1.x)
# print(p1.y)
# print(p1,p2)

#花色和数字
# Card = namedtuple('card',['suits','number'])
# c1 = Card('红桃',2)
# print(c1)
# print(c1.number)
# print(c1.suits)

#队列
# import queue
# q = queue.Queue()
# q.put([1,2,3])
# q.put(5)
# q.put(6)
# print(q)
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get())   # 阻塞
# print(q.qsize())

# from collections import deque
# dq = deque([1,2])
# dq.append('a')   # 从后面放数据  [1,2,'a']
# dq.appendleft('b') # 从前面放数据 ['b',1,2,'a']
# dq.insert(2,3)    #['b',1,3,2,'a']
# print(dq.pop())      # 从后面取数据
# print(dq.pop())      # 从后面取数据
# print(dq.popleft())  # 从前面取数据
# print(dq)

#有序字典
# from collections import  OrderedDict
# od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# print(od) # OrderedDict的Key是有序的
# print(od['a'])
# for k in od:
#     print(k)

# from collections import defaultdict
# d = defaultdict(lambda : 5)
# print(d['k'])

3, time module

formatted time - string: for people to see
timestamp time - float time: for computer to see
structured time - tuple: for calculation

Convert between time, date, timestamp
1. Convert the time of the string to a timestamp
Method:
a = "2013-10-10 23:40:00"
Convert it to a time array
import time
timeArray = time.strptime( a, "%Y-%m-%d %H:%M:%S")
to timestamp:
timeStamp = int(time.mktime(timeArray))
timeStamp == 1381419600

2. String format change
such as a = "2013-10-10 23:40:00", want to change to a = "2013/10/10 23:40:00"
method: first convert to time array, then convert to other formats
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M: %S", timeArray)

3. Convert the timestamp to the specified format date:
Method 1:
Use localtime() to convert to a time array, and then format it to the required format, such as
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime(“% Y-%m-%d %H:%M:%S", timeArray)
otherStyletime == "2013-10-10 23:40:00"

方法二:
import datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime(“%Y-%m-%d %H:%M:%S”)
otherStyletime == “2013-10-10 23:40:00”

4. Get the current time and convert it to the specified date format
Method 1:
import time
to get the current time timestamp
now = int(time.time()) -> this is the timestamp
converted to other date formats, such as: "%Y-% m-%d %H:%M:%S”
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime(“%Y-%m-%d %H:%M:%S”, timeArray)

Method 2:
import datetime
to get the current time
now = datetime.datetime.now() -> this is the time array format
Convert to the specified format:
otherStyleTime = now.strftime(“%Y-%m-%d %H:%M :%S”)

5. Get the time three days ago
Method:
import time
import datetime
First get the date in time array format
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
Convert to timestamp:
timeStamp = int( time.mktime(threeDayAgo.timetuple()))
convert to other string format:
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
Note: parameter of timedelta() There are: days, hours, seconds, microseconds

6. Given a timestamp, calculate the time a few days ago:
timeStamp = 1381419600
first convert to datetime
import datetime
import time
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
Reference 5, can be converted to other arbitrary formats

Time and date formatting symbols in python:
%y two-digit year representation (00-99)
%Y four-digit year representation (000-9999)
%m month (01-12)
%d day of the month ( 0-31)
%H 24-hour hour (0-23)
%I 12-hour hour (01-12)
%M minutes (00=59)
%S seconds (00-59)
%a local simplified weekday Name
%A Local full week name
%b Local simplified month name
%B Local full month name
%c Local corresponding date representation and time representation
%j Day of the year (001-366)
%p Local AM or PM equivalent %U Week number of the year ( 00-53
) Sunday is the start of the week
%w Week (0-6), Sunday is the start
of the week %W Week number of the year (00-53) Monday is the week The start of
%x local corresponding date represents
%X local corresponding time represents
%Z name of current time zone
%% % sign itself

# print(time.strftime("%Y-%m-%d %a %H:%M:%S"))  #year month day HOUR MINUTE SECOND
# print(time.strftime("%Y/%m/%d %H:%M:%S"))  #year month day HOUR MINUTE SECOND
# print(time.strftime("%m-%d %H:%M:%S"))  #year month day HOUR MINUTE SECOND
# print(time.strftime("%H:%M:%S"))  #year month day HOUR MINUTE SECOND
# print(time.strftime("%H:%M"))  #year month day HOUR MINUTE SECOND


# struct_time = time.localtime()
# print(struct_time)
# print(struct_time.tm_year)

import time
# 时间戳和结构化时间
# t = time.time()
# print(t)
# print(time.localtime(3000000000))
# print(time.gmtime(t))

# print(time.mktime(time.localtime()))

# print(time.strptime('2000-12.31','%Y-%m.%d'))
# print(time.strftime('%m/%d/%Y %H:%M:%S',time.localtime(3000000000)))

# print(time.asctime())

4, random module

The most commonly used functions are as follows:
random.randint
random.randint (1,10)
The meaning of the statement is to generate a random number (integer int type) from 1 to 10 (including 1 and 10). (The parameter is an integer and cannot be a floating-point number, otherwise an error will be reported)
random.randint(20, 10) #This statement is wrong. The lower bound must be less than or equal to the upper bound.
random.random
random.random()
generates a random floating point number between 0 and 1, including 0 but not including 1, i.e. [0.0, 1.0).
random.uniform
random.uniform(a, b)
generates a random floating point number between a and b. However, unlike randint, a and b can be non-integers and do not need to consider the size.
That is,
random.uniform(3.65, 10.56)# can be like this
random.uniform(10.56, 3.65)# can also be like this
random.choice
random.choice(seq)
randomly selects an element from the sequence. seq needs to be a sequence, such as list, tuple, string.
random.choice([1, 2, 3, 5, 8, 13]) #list
random.choice('hello')
#string random.choice(['hello', 'world']) #composed of strings list
random.choice((1, 2, 3)) #tuple
are all possible uses.
random.randrange
random.randrange(start, stop, step)
generates a random integer from start to stop (excluding stop), with an interval of step. start, stop, and step must be integers, and start is less than stop.
random.sample
random.sample(p, k)
randomly obtains k elements from the p sequence and generates a new sequence. sample does not change the original sequence.
This module is very 666, and also supports triangular, beta distribution, exponential distribution, gamma distribution, Gaussian distribution and other very professional random algorithms.
random.shuffle
random.shuffle(x) shuffles
the elements in the sequence x. Shuffle directly changes the original sequence. Such as:

import random
a=[1,2,3,4,5,6]
random.shuffle(a)
print(a)

The results are as follows:
[5, 1, 3, 6, 4, 2]
Novices may encounter some errors when using this function, as follows:

import random
a=[1,2,3,4,5,6]
print(random.shuffle(a))

Using this method will result in None, because random.shuffle() is used to shuffle the list elements and has no return value, so you cannot use print(random.shuffle(a)) to output the shuffle


5, os module

The role of the os module:

  os, the semantics is the operating system, so it must be a function related to the operating system. It can handle files and directories that we need to do manually every day, such as: display all files in the current directory/delete a file/get the file size ...

  In addition, the os module is not limited by the platform, that is to say: when we want to display the current path in linux, we need to use the pwd command, and we need to use this command in the cmd command line in Windows, er... I wipe, I still I really don't know, (no matter what, it's definitely not pwd), at this time we use the os.path.abspath(name) function of the os module in python, no matter whether it is Linux or Windows, we can get the current absolute path.

Common functions of the os module:

1 os.name #Display the currently used platform

2 os.getcwd() #Display the current python script working path

3 os.listdir('dirname') #Return all file and directory names in the specified directory

4 os.remove('filename') #delete a file

5 os.makedirs('dirname/dirname') #Multi-layer recursive directory can be generated

6 os.rmdir('dirname') #delete single-level directory

7 os.rename("oldname","newname") #Rename the file

8 os.system() #Run the shell command, note: here is to open a new shell, run the command, when the command ends, close the shell

9 os.sep #Display the path separator under the current platform

10 os.linesep # gives the line terminator used by the current platform

11 os.environ #Get system environment variables

12 os.path.abspath(path) #Display the current absolute path

13 os.path.dirname(path) #Return the parent directory of the path

14 os.path.basename(path) #Return the last directory or file of the path, if the path ends with / or \, then it will return a null value.

15 os.path.isfile(path) #If path is a file, return True

16 os.path.isdir(path) #If path is a directory, return True

17 os.stat() #Get file or directory information

18 os.path.split(path) #Split path into path name and file name. (In fact, if you use directories at all, it will also separate the last directory as the filename, and it won't tell if the file or directory exists)

19 os.path.join(path,name) #The result of connecting directory and file name or directory is path/name

import  os
# print(os.getcwd())
# os.chdir(r'C:\Users\Administrator\PycharmProjects')
# print(os.getcwd())

# os.chdir('..')
# print(os.getcwd())
# os.makedirs('dirname1/dirname2')
# os.removedirs('dirname1/dirname2')

# os.mkdir('dirname1/dirname')

# print(os.listdir(r'C:/Users/Administrator/PycharmProjects/s9'))

# print(os.stat('1.复习.py'))

# print(os.sep)  # python代码跨平台 :linux windows
# /user/bin/

# os.system("dir")
# ret = os.popen("dir").read()
# print(ret)

# print(os.environ)

# print(os.getcwd())
# print(os.path.split(os.getcwd()))

# print(os.path.join(r'C:\Users\Administrator','user','local'))
# print(os.getcwd())
# print(os.path.getsize(os.path.join(os.getcwd(),'1.复习.py')))

6, sys module

List of common functions of the sys module
sys.argv: Implements passing arguments to the program from outside the program.

sys.exit([arg]): Exit in the middle of the program, arg=0 is a normal exit.

sys.getdefaultencoding(): Get the current encoding of the system, generally the default is ascii.

sys.setdefaultencoding(): Set the default encoding of the system, this method will not be seen when executing dir(sys), if the execution fails in the interpreter, you can execute reload(sys) first, and then execute setdefaultencoding('utf8'), this When the system default encoding is set to utf8. (see Setting the System Default Encoding)

sys.getfilesystemencoding(): Get the encoding method used by the file system. It returns 'mbcs' under Windows and 'utf-8' under mac.

sys.path: Get the string collection of the specified module search path, you can put the written module under a certain path obtained, and you can find it correctly when importing in the program.

sys.platform: Get the current system platform.

sys.stdin, sys.stdout, sys.stderr: The stdin , stdout , and stderr variables contain stream objects corresponding to standard I/O streams. If you need finer control over the output, and print doesn't do what you want, they are for you required. You can also replace them, in which case you can redirect output and input to other devices, or handle them in a non-standard way

import sys
# print(sys.platform)
# print(sys.version)


# print(sys.path.clear())


ret = sys.argv
name = ret[1]
pwd = ret[2]
if name == 'alex' and pwd == 'alex3714':
    print('登陆成功')
else:
    print("错误的用户名和密码")
    sys.exit()
print('你可以使用计算器了')

Related Posts