A summary of 12 basic knowledge points in the Python language _python

Source: Internet
Author: User
Tags print format readline svn in python

A summary of 12 basic knowledge commonly used in Python programming: regular expression substitution, traversal directory method, list sorted by column, go to Heavy, dictionary sort, dictionary, list, string interchange, Time object operation, command line parameter parsing (getopt), print formatted output, transform into system, Python invokes system commands or scripts, Python reads and writes files.

1, Regular expression replacement

Goal: Replace Overview.gif in string line with other strings

Copy Code code as follows:
>>> line = ' '
>>> Mo=re.compile (R ' (? <=src=) "([\w+\.] +) "', Re. I)

>>> mo.sub (R ' "\1****", line)
'

>>> mo.sub (R ' replace_str_\1 ', line)
"

>>> mo.sub (R ' "Testetstset", line)
'


Note: Where \1 is the data that is matched to, it can be directly referenced in this way

2, traverse the directory method

At some point, we need to traverse a directory to find a specific list of files that can be traversed through the Os.walk method, which is very convenient

Copy Code code as follows:
Import OS
FileList = []
RootDir = "/data"
For root, subfolders, the files in Os.walk (RootDir):
If '. SVN ' in SubFolders:subFolders.remove ('. SVN ') # Exclude specific directories
For file in Files:
If File.find (". t2t")!= -1:# find files for a specific extension
File_dir_path = Os.path.join (root,file)
Filelist.append (File_dir_path)

Print FileList

3. List by column (listing sort)

If each element of the list is a tuple (tuple), we want to sort by a column of tuples, and we can refer to the following methods
The following examples are sorted according to the 2nd and 3rd columns of the tuple, and are in reverse order (reverse=true)

Copy Code code as follows:
>>> 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 ', 6429600, ' 0.0 ')]

4, list to be heavy (lists Uniq)

Sometimes you need to delete the duplicate elements in the list by using the following methods

Copy Code code as follows:
>>> 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 according to the key of the dictionary, but if we want to sort by the value of the dictionary, we use the following method

Copy Code code as follows:
>>> 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 ')]

6, dictionary, list, string to turn

The following is the build database connection string, converted from dictionary to string

Copy Code code as follows:
>>> 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
Copy Code code as follows:
>>> 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 a Time object to a string

Copy Code code as follows:
>>> Import datetime
>>> Datetime.datetime.now () strftime ("%y-%m-%d%h:%m")
' 2011-01-20 14:05 '

Time Size comparison
Copy Code code as follows:
>>> 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, calculate 8 hours ago
Copy Code code as follows:
>>> 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 '

Converts a string into a time object
Copy Code code as follows:
>>> endtime=datetime.datetime.strptime (' 20100701 ', "%y%m%d")
>>> type (endtime)
<type ' Datetime.datetime ' >
>>> Print Endtime
2010-07-01 00:00:00

Format output from 1970-01-01 00:00:00 UTC to the current number of seconds
Copy Code code as follows:

>>> 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)

In general, when writing some daily operation scripts, you need to enter different command-line options to implement different functions depending on the conditions
The getopt module in Python provides a good way to parse the command-line arguments, as explained below. Please see the following procedure:

Copy Code code as follows:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import sys,os,getopt
def usage ():
print ' '
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-stock code
-n:stock Name
-s:stock Code
-h:this Help Info
Test.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"% arg
elif opt = = ' F ':
Print "read file%s"% arg
elif opt = = ' C ':
print ' user-defined%s '% arg
elif opt = = ' E ':
print ' Exchange Name%s '% arg
elif opt = = ' s ':
Print "Stock code%s"% arg
elif opt = = ' n ':
print ' Stock name%s '% arg

Sys.exit ()

9, print format output

9.1. Format output string
intercepts the string output, the following example will output only the first 3 letters of the string

Copy Code code as follows:
>>> str= "ABCDEFG"
>>> print "%.3s"% str
Abc

According to the fixed-width output, not enough space to fill, the following example output width of 10
Copy Code code as follows:
>>> str= "ABCDEFG"
>>> print "%10s"% str
Abcdefg

Intercept string, output in fixed width
Copy Code code as follows:
>>> str= "ABCDEFG"
>>> print "%10.3s"% str
Abc

Floating-point type data digits reserved
Copy Code code as follows:
>>> Import Fpformat
>>> a= 0.0030000000005
>>> B=fpformat.fix (a,6)
>>> Print B
0.003000

Rounding floating-point numbers, mainly using the round function
Copy Code code as follows:
>>> from decimal Import *
>>> a = "2.26"
>>> B = "2.29"
>>> c = Decimal (a)-decimal (b)
>>> Print C
-0.03
>>> C/decimal (a) * 100
Decimal ('-1.327433628318584070796460177 ')
>>> Decimal (str (Round (C/decimal (a) * 100, 2))
Decimal ('-1.33 ')

9.2, the conversion of the system

There are times when you need to make different transitions, and you can refer to the example below (%x 16,%d decimal,%o Decimal

Copy Code code as follows:
>>> num = 10
>>> print "Hex =%x,dec =%d,oct =%o"% (num,num,num)
Hex = A,dec = 10,oct = 12

10. Python invokes system commands or scripts

Using Os.system () to invoke system commands, the output and return values are not available in the program

Copy Code code as follows:
>>> Import OS
>>> Os.system (' ls-l/proc/cpuinfo ')
>>> Os.system ("Ls-l/proc/cpuinfo")
-r--r--r--1 root 0 March 16:53/proc/cpuinfo
0

Using Os.popen () to invoke the system command, the command output can be obtained in the program, but the return value performed cannot be obtained
Copy Code code as follows:
>>> out = Os.popen ("Ls-l/proc/cpuinfo")
>>> Print Out.read ()
-r--r--r--1 root 0 March 16:59/proc/cpuinfo

Use Commands.getstatusoutput () to invoke the System command, in which the command output and the return value of execution can be obtained
Copy Code code as follows:
>>> Import Commands
>>> commands.getstatusoutput (' Ls/bin/ls ')
(0, '/bin/ls ')

11, Python capture user Ctrl + C, ctrl+d events

Sometimes, you need to capture user keyboard events in your program, such as CTRL + C exit, so you can safely exit the program

Copy Code code as follows:
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

Read the file to the list once, the speed is faster, the applicable file is relatively small case

Copy Code code as follows:
Track_file = "Track_stock.conf"
FD = open (Track_file)
Content_list = Fd.readlines ()
Fd.close ()
For line in Content_list:
Print Line

Read-by-line, slow, suitable for not enough memory to read the entire file (the file is too large)
Copy Code code as follows:
FD = open (File_path)
Fd.seek (0)
title = Fd.readline ()
Keyword = fd.readline ()
UUID = Fd.readline ()
Fd.close ()

The difference between writing a file and Writelines

Fd.write (str): Write str to a file and write () does not add a newline character after Str
Fd.writelines (content): The content of the contents of all written to the file, write-as-is, do not add anything after each line

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.