12 basic knowledge commonly used in Python programming: regular expression substitution, traversal of directory methods, list sorting by column, de-weight, dictionary ordering, dictionary, list, string reciprocal, time object manipulation, command-line argument parsing (getopt), print format output, binary conversion, Python calls system commands or scripts, and Python reads and writes files.
1. Regular expression substitution
Target: Replace Overview.gif in string line with other strings
>>> line = ' >>> mo=re.compile (R ' (? <=src=) "([\w+\.] +) "', Re. I) >>> mo.sub (R ' "\1****" ', line) ' >>> mo.sub ( R ' Replace_str_\1 ', line) ' "</span> >>> mo.sub (R ' "Testetstset" ', line) '
Note: Where \1 is the data that is matched to, you can refer directly to it in such a way
2. Traverse Directory method
At some point, we need to traverse a directory to find a specific list of files that can be traversed by the Os.walk method, which is very convenient
Import Osfilelist = []rootdir = "/data" for root, subfolders, files in Os.walk (RootDir): if '. SVN ' in Subfolders:subfolders . Remove ('. SVN ') # Exclude a specific directory for file: if File.find (". t2t")! = -1:# Find a file with a specific extension File_dir_path = Os.path.join (root,file) filelist.append (file_dir_path) print fileList
3. List sorted by columns (list sort)
If each element of the list is a tuple (tuple), and we want to sort by a column of tuples, refer to the following method
In the following example we are sorted by the tuple's 2nd and 3rd columns, and are in reverse order (reverse=true)
>>> a = [(' 2011-03-17 ', ' 2.26 ', 6429600, ' 0.0 '), (' 2011-03-16 ', ' 2.26 ', 12036900, '-3.0 '), (' 2011-03-15 ', ' 2.33 ', 15615500, ' -19.1 ')]>>> print a[0][0]2011-03-17>>> B = Sorted (A, Key=lambda result:result[1],reverse= True) >>> print b[(' 2011-03-15 ', ' 2.33 ', 15615500, ' 19.1 '), (' 2011-03-17 ', ' 2.26 ', 6429600, ' 0.0 '), (' 2011-03-16 ', ' 2.26 ', 12036900, ' -3.0 ')]>>> C = Sorted (A, Key=lambda result:result[2],reverse=true) >> > Print c[(' 2011-03-15 ', ' 2.33 ', 15615500, '-19.1 '), (' 2011-03-16 ', ' 2.26 ', 12036900, '-3.0 '), (' 2011-03-17 ', ' 2.26 ', 6 429600, ' 0.0 ')]
4, list to go to heavy (lists Uniq)
Sometimes you need to delete the duplicate elements in the list by using the following method
>>> lst= [(1, ' SSS '), (2, ' fsdf '), (1, ' SSS '), (3, ' fd ')]>>> set (LST) set ([(2, ' fsdf '), (3, ' fd '), (1, ' SSS ') )] >>>>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]>>> set (LST) set ([1, 3, 4, 5, 6, 7])
5. Dictionary sort (dict sort)
In general, we sort by the dictionary key, but if we want to sort by the value of the dictionary, we use the following method
>>> from operator import itemgetter>>> AA = {"A": "1", "SSS": "2", "FFDF": ' 5 ', "ffff2": ' 3 '}>>> Sort_aa = sorted (Aa.items (), Key=itemgetter (1)) >>> sort_aa[(' A ', ' 1 '), (' SSS ', ' 2 '), (' Ffff2 ', ' 3 '), (' Ffdf ', ' 5 ')]
From the running results above, the value of the dictionary is sorted according to the
6, dictionary, list, String mutual transfer
The following is the build database connection string, converting from dictionary to string
>>> params = {"Server": "Mpilgrim", "Database": "Master", "UID": "sa", "pwd": "Secret"}>>> ["%s=%s"% (K, V) for K, V in Params.items () [' Server=mpilgrim ', ' uid=sa ', ' database=master ', ' Pwd=secret ']>>> ";". Join (["%s=%s"% (k, v) for K, V in Params.items ()]) ' Server=mpilgrim;uid=sa;database=master;pwd=secret '
The following example converts a string into a dictionary
>>> a = ' server=mpilgrim;uid=sa;database=master;pwd=secret ' >>> AA = {}>>> for i in A.split ('; ') ): aa[i.split (' = ', 1) [0]] = i.split (' = ', 1) [1]...>>> aa{' pwd ': ' Secret ', ' database ': ' Master ', ' uid ': ' sa ', ' Server ': ' Mpilgrim '}
7. Time Object operation
Convert time objects to strings >>> import datetime>>> Datetime.datetime.now (). Strftime ("%y-%m-%d%h:%m") ' 2011-01-20 14:05 ' time size comparison >>> import time>>> t1 = Time.strptime (' 2011-01-20 14:05 ', "%y-%m-%d%h:%m") >>> t2 = time.strptime (' 2011-01-20 16:05 ', "%y-%m-%d%H:%M" ) >>> T1 > T2 false>>> T1 < T2 True time difference calculation, calculated 8 hours ago >>> datetime.datetime.now (). strftime ("%y-%m-%d%h:%m") ' 2011-01-20 15:02 ' >>> (Datetime.datetime.now ()-Datetime.timedelta (hours=8)). Strftime ("%y-%m-%d%h:%m") ' 2011-01-20 07:03 ' Convert string to time object >>> endtime=datetime.datetime.strptime (' 20100701 ', '%y%m%d ') >>> type (endtime) <type ' datetime.datetime ' >>>> print endtime 2010-07-01 00:00:00 will be from 1970-01-01 00:00:00 UTC to present Number of seconds, formatted output >>> import time>>> a = 1302153828>>> time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (a)) ' 2011-04-07 13:23:48 '
8, command-line parameter parsing (getopt)
Usually in the writing of some of the day operation of the script, you need to enter different command line options according to different conditions to achieve different functions in Python provides the getopt module good implementation of the command line parameter parsing, the following distance description. Please see the following procedure:
#!/usr/bin/env python#-*-coding:utf-8-*-import sys,os,getoptdef usage ():p rint "" Usage:analyse_stock.py [options]. .] Options:-e:exchange name-c: user-defined Category name-f: Read stock info from file and save to db-d: Delete from db By the stock code-n: Stock name-s: Stock code-h: This help infotest.py-s haha-n "ha Ha" ' try:opts, args = getopt.getopt (sys.argv[1:], ' he:c:f:d:n:s: ') except getopt. Getopterror:usage () sys.exit () If Len (opts) = = 0:usage () sys.exit () for OPT, arg in opts:if opt in ('-H ', '--help '):
usage () sys.exit () elif opt = = '-d ': print "Del stock%s"% argelif opt = = '-F ': print "read file%s"% Argeli f opt = = '-C ': print "user-defined%s"% argelif opt = = '-E ': print "Exchange Name%s"% argelif opt = = '-S ':
print "Stock code%s"% argelif opt = = '-n ': print "stock name%s"% arg sys.exit ()
9. Print formatted output
9.1. Formatted output string
To intercept the string output, the following example will only output the first 3 letters of the string >>> str= "ABCDEFG" >>> print "%.3s"% str ABC is output at a fixed width, with insufficient space complement, The following example output width is 10>>> str= "ABCDEFG" >>> print "%10s"% str ABCDEFG intercept string, according to fixed width output >>> str= " ABCDEFG ">>> print"%10.3s "% str ABC float type data bits reserved >>> import fpformat>>> a= 0.0030000000005 >>> B=fpformat.fix (a,6) >>> print B 0.003000 rounding of floating-point numbers, mainly using the round function >>> from decimal Import *>>> a = "2.26" >>> B = "2.29" >>> c = Decimal (a)-Decimal (b) >>> print C -0.03 >>> C/decimal (a) * decimal (' -1.327433628318584070796460177 ') >>> decimal (str (round (c/ Decimal (a) * 2)) decimal ('-1.33 ')
9.2. Binary conversion
There are times when you need to make a different conversion, you can refer to the following example (%x 16,%d decimal,%o Decimal
>>> num = 10>>> print "hex =%x,dec =%d,oct =%o"% (num,num,num) Hex = A,dec = 10,oct = 12
10. Python calls system commands or scripts
Using Os.system () to invoke system commands, the program cannot get output and return values >>> import os>>> os.system (' ls-l/proc/cpuinfo ') >>> OS . System ("Ls-l/proc/cpuinfo") -r--r--r--1 root root 0 March 16:53/proc/cpuinfo 0 Use Os.popen () to invoke the System command, the program can be To get command output, but cannot get execution return value >>> out = Os.popen ("ls-l/proc/cpuinfo") >>> print Out.read () -r--r--r--1 Root root 0 March 16:59/proc/cpuinfo use Commands.getstatusoutput () to invoke system commands, which can get the return value of command output and execution >>> Import commands>>> commands.getstatusoutput (' Ls/bin/ls ') (0, '/bin/ls ')
11, Python capture user Ctrl + C, Ctrl+d event
Sometimes, you need to capture user keyboard events in the program, such as CTRL + C exit, so that you can better safely exit the program
Try: Do_some_func () except Keyboardinterrupt: print "user press ctrl+c,exit" except Eoferror: print "user Press Ctrl+d,exit "
12. Python Read and write files
One-time read into the file to the list, faster, suitable for the file is relatively small case track_file = "track_stock.conf" FD = open (track_file) content_list = Fd.readlines () fd.close () for lines in content_list: The print line reads progressive, slow, not enough memory to read the entire file (file too Large) fd = open (file_path) fd.seek (0) title = Fd.readline () keyword = fd.readline () uuid = Fd.readline () fd.close () writes the difference between write file and Writelines fd.write (str): Writes STR to a file, write () does not add a newline character fd.writelines (content) after Str: writes the contents to the file, writes it as is, and does not add anything behind each line