Common Module Upgrade

  A, collection module

  Two, time module

  Three, random module

  Four, os and sys mo module

  V. serialization and deserialization json module

  Six, subprocess module

 

  A, collection module

  1.1 namedtuple (named grouping)

# 1 may represent two and three dimensional coordinates 
# from Collections Import namedtuple 
# 
# Point = namedtuple ( 'coordinates', [ 'x', ' y', 'z']) # The first field is the name of the second parameter objects that can be iterative 
# 
# P = Point (1, 2,4) 
# Print (P) # coordinates (X =. 1, Y = 2, Z =. 4) 


# 2. shuffling 
# from Collections Import namedtuple 
# T = namedtuple ( 'poker', 'Color NUM') 
# T1 = T ( 'spade', 'A') 
# Print (t1.color) 
# Print (t1.num) 
# L = [90,1,2,9 , 4,5,8,23,42,5,6] 
# Import Random 
# Random.shuffle (L) 
# Print (L) 

# 
# # corresponding figures
# R & lt namedtuple = ( 'Japanese', 'Person name size') 
# R1 = R & lt ( 'Tokyo', 'Miyazaki', 'm') 
# Print (R1)
# 2.queue (:) and the deque queue () deque
# 2.queue (queue) 
# queue: FIFO 
# L = [12,22,33,44] 
# Import Queue 
# Mr # as an object 
# Q = Queue.Queue () 
# # value which added to the queue 
# q.put ( '. 1') 
# q.put ( '2') 
# q.put ( '. 3') 
# q.put ( '. 4') 

# toward the value of the queue to 
# Print (q.get ()) 
# Print (q.get ()) 
# Print (q.get ()) 
# Print (q.get ()) 
# Print (q.get ()) # no value the get () will wait until a user by value, until wait until 

# the deque deque: deque is called both sides are out of 
# from the deque Import Collections 
#q = deque ([ 'a' , 'b', 'c']) # deque outer layers are in parentheses 
# q.append (. 1) 
# q.append (2) 
# q.appe Nd (. 3) 
# Print ( q) # [ 'a', 'b', 'c', 1, 2, 3] was added a heavy tail 

# appendlef () 
# q.appendleft (2) 
# Print (Q, type (Q)) # 
# Q .popleft () 
# q.popleft (1) # popleft () to remove elements do not pass argument 
# Print (q)

  

# 3.orderedDict (ordered dictionary)
# 和正常字典做对比
# from collections import OrderedDict
# normal_dic = {'name':'coc','age':18}
# order_d = OrderedDict([('a',1),('b',2),('b',3)])
# print(order_d,type(order_d))
# order_d['x'] = 1
# order_d['y'] = 2
# order_d['z'] = 3
# for i in order_d:
#     print(i)

  


# 4.defaultDict (default dictionary)
= values [. 11, 22 is, 33,44,55,66,77,88,99,90 ]
 # greater than the value of 66 is added to the first value to the dictionary not empty list 
# usage prior to 
# Method a: 
# DIC = { 'K1': [], "K2": []} 
# for I in values: 
#      IF I> 66: 
#          . DIC [ 'K1'] the append (I) 
#      the else: 
#          DIC [ 'K2 '] .append (i) 
# Print (dic) 

# method two: 
# can not set the default [] list, and how to do it: >> coincidence just have defaultdict () 
# (default is enter what you type is what type) of the subsequent dictionary values corresponding to the new Key is the default list 
# from a defaultdict Import Collections 
# 
# my_dic = a defaultdict (list) 
# # print(my_dic[''])  # []
# # print(my_dic['yyy'])  # []
# for i in values:
#     if i>66:
#         my_dic['k1'].append(i)
#     else:
#         my_dic['k2'].append(i)
# print(my_dic)
#

  

# 5.Counter (String counter): directly in the form of a dictionary

 
# Counting the number appearing in the string and the number of dots to a value 

S = ' qwwwqqqeee ' 
# Method a: 
# DIC = {} 
# for I in S: 
#      IF I in DIC: 
#          DIC [I] + =. 1 
# 
#      the else: 
#          DIC [I] =. 1 
# Print (DIC) 
# method two: 
from Collections Import Counter 
L = dict (Counter (S))   # can be transferred directly 
Print (L)
 #
 DIC = {}
 for I in l.items ():   #Internal principle 
    DIC [I [0]] = I [. 1 ]
 Print (DIC)
Second, the time module
  
"" " 
Three forms
1. stamp
2. The time format (used to display the posters)
3. Structure of time
" ""
Conversion string # 
# Import Time 
# The time.strftime RES = ( '% Y-M-%%% X-D') # 2019-07-18 20:39:43 
# Print (RES) # 2019-07-18 20:33:37 
# 

# datetime 

# Import datetime 
# 
# datetime.date.today RES1 = () # 2019-07-18 
# datetime.datetime.today RES2 = () # 20 is 2019-07-18: 39: 43.402935 
# 
# 
# Print (res1) 
# Print (RES2) 
# Print (res2.isoweekday ()) # 4 Thursday 
# print (res1.month, res1.year, res1.day ) # 7 July: 2019: day: 18 

# UTC standard time 
Import datetime 
day_t = datetime.datetime.utcnow () 
Print (day_t) # 2019-07-18 12: 42: 59.687143 East eight districts

  Three, random module


"" "
Uppercase letter lowercase alphanumeric

5-digit random codes
CHR
The random.choice
encapsulated into a function, the user would like to generate several generates several
" ""
 
GET_CODE EF (n-): 
    code = '' 
    for I in Range (n-):
         # Mr uppercase to lowercase random numbers 
        upper_str = CHR (the random.randint (65, 90, )) 
        lower_str = CHR (the random.randint (97,122 )) 
        random_int = STR (the random.randint (0,9 ))
         # randomly selected from a three above as a random one of the codes 
        # the random.choice () method is a 
        code + = the random.choice ([upper_str , lower_str, random_int])
     return code 
RES = GET_CODE (. 4 )
 Print (RES)
 

  Four, os and sys module

# Os module: dealing with the operating system module 
# sys module: dealing with python interpreter
  4.1os commonly used methods:
# # By listdir () to get all the files under the File 
Import os
 # os.mkdir ( 'Tomorrow Content') # Create a folder 
# 2.os.exists () 
# Print (os.path.exists ( 'D: \ datas \ day16 \ works today \ coco.txt ')) # determine the file / folder exists 

# 3.os.isfile () 
# Print (os.path.isdir (' D: \ datas \ day16 \ work today ' )) # determine whether there is a folder 

# 4. 
# os.getcwd () 
Print (os.getcwd ())   # D: \ DATAS \ day16 view the file directory path of the current file to run 

Print (os.chdir ( ' D: \ datas \ day16 \ work today ' ))
 Print (os.getcwd ())   # D: \ datas \ day16 \ today works to switch the current directory 
Print (os.path.getsize (' D: \ DATAS \ day16 \ works today \ coco.txt ' ))   # number of bytes

  Real columns:

# Os commonly used methods: 
# demand to open the contents of the file (download movies): 
# Path splicing file: 
# Import os 
# base_dir = os.path.dirname (__ file__) # current location as long as the os module layer a 
# project folder path where the file #: 
# MOVIE_LIST_DIR = os.path.join (base_dir, 'today works') # splicing only to only to the current movie directory, no filename 
# 
# # by listdir () to get the next file All documents 
# movie_list = os.listdir (MOVIE_LIST_DIR) # 

# for index, movie in the enumerate (movie_list, 1): 

#      Print (index, movie) 
# Choice = the iNPUT ( 'enter the movie index (today recommended tank hot search)> >>: ') Strip (). 
# IF choice.isdigit (): 
#      Choice = int (Choice) 
#     Choice in the Range IF (1, len (movie_list) +1): 
#          filename # want to get the user's 
#          target_name = movie_list [Choice-1] # fetch index 
# 
#          # stitching absolute file path 
#          target_name_path = os.path .join (MOVIE_LIST_DIR, target_name) 
#          # open the file 
#          with open (target_name_path, 'R & lt', encoding = 'UTF-. 8') AS F: 
#              for in Line F: 
#                  Print (Line)

  4.2 sys module

# Sys.path.append () # Adding an environment variable to the system environment variables 

print (sys.version) # 3.6.4 (v3.6.4 : d48eceb, Dec 19 2017, 06:54:40) [MSC v. 64-bit 1900 (AMD64)]

Print (sys.argv) # command line to start the file can be done to verify the identity of the
IF len (sys.argv) <= 1:
Print ( 'Please enter your username and password')
the else:
username = SYS. the argv [. 1]
password = the sys.argv [2]
IF username == 'Jason' and password == '123':
Print ( 'Welcome')
# py this current document logic code
the else:
Print ( 'user does not exist can not be execution of the current file ')

 

  Five, json module:

  Serialization and de-serialization:

  5.1 What is the sequence of: 

  Serialization 
  Sequence: string
  sequence of: converting a character string into other data types during

  the data string must be written to the file
  -based data transmission network must be binary

5.2 What is deserialized:
 
       Serialization: Other types of data translated into strings during 
   deserialization: string converted to other data types

  5.3 json serialized data types can be:
  
  json module (******) 
  all languages support json format
  supported data types rarely list of strings dictionary integer tuple (turn into a list) Boolean value
  The pickle module (****) 
  only supports Python
  Python supports all data types
 Real columns:
  
mport json
with open(r'D:\datas\day16\1.txt','rt',encoding='utf-8')as f:
    # f方法一:
    # for line in f:
    #  ic = json.loads(res)
    # user_dic1 = json.load(f)
    # print(user_dic)
    # print(user_dic1)
    # print(user_dic)
    # for line in f:
    #     user_dic = json.loads(line)
    #     print(user_dic)

    # res = f.read()
    # user_dic =json.loads(res)
    # print(user_dic)
    # user_dic = json.load(f)
    # print(user_dic)
  Summarizes the problems encountered today: 

  1. When writing is randomly generated verification code will forget num = random.randint (0,9) because we want to turn into a string spliced into a string alp_lower = chr (random.randint (65 , 90)
  2. in the os.listdir write file () all files in the directory will change print; for index, moive in enumerate ( ) behind the increase in the index start = 1 will be changed from a start sequence
  3, in the file name when selecting movie_list must choice-1 because moive_List [choice] is an index so you want to start 1-indexed default is 0 otherwise fail to file
  4. write json module serialization and de-serialization when
  summarize methods of operation:
    serialization: json.dumps () dunmps () is converted into a string of other types of data directly to a file
    deserialize: json.laods () is the read character string to a digital type of original deposit: Note that if the file a plurality of sets of memory recall for each row are cyclically acquired by the string
      res = f.read () single-line
      for in line F:
        user_dic = json.loads (line)
     json.loads (RES / line)
    

  # Dump (): Serialization: The data type is able to parse json data types: dict lsit, string, plastic, BOOL, turn into a tuple in the list of objects json,

   res = json.dump (user_dic, f) through the file object handles written document

   load () of the string stored deserialized data type (user_dic) deserialize operation file.

 

      picle () when the note is written in binary, keep the object obj

  json purpose in what way short existence, has made time to give me what type of data is returned

  

 
 
 



Guess you like

Origin www.cnblogs.com/mofujin/p/11210930.html