溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python語言常用基礎(chǔ)知識點(diǎn)是什么

發(fā)布時間:2022-05-18 11:46:12 來源:億速云 閱讀:118 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“Python語言常用基礎(chǔ)知識點(diǎn)是什么”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

python編程中常用的12種基礎(chǔ)知識總結(jié):正則表達(dá)式替換,遍歷目錄方法,列表按列排序、去重、字典排序、字典、列表、字符串互轉(zhuǎn),時間對象操作,命令行參數(shù)解析(getopt),print  格式化輸出,進(jìn)制轉(zhuǎn)換,Python調(diào)用系統(tǒng)命令或者腳本,Python 讀寫文件。

1、正則表達(dá)式替換

目標(biāo): 將字符串line中的 overview.gif 替換成其他字符串。

>>> line = '<IMG ALIGN="middle" SRC=\'#\'" />' >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  >>> mo.sub(r'"\1****"',line) '<IMG ALIGN="middle" SRC=\'#\'" /span> >>> mo.sub(r'replace_str_\1',line) '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span> >>> mo.sub(r'"testetstset"',line) '<IMG ALIGN="middle" SRC=\'#\'" /span>

注意: 其中 \1 是匹配到的數(shù)據(jù),可以通過這樣的方式直接引用。

2、遍歷目錄方法

在某些時候,我們需要遍歷某個目錄找出特定的文件列表,可以通過os.walk方法來遍歷,非常方便。

import os fileList = [] rootdir = "/data" for root, subFolders, files in os.walk(rootdir): if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目錄 for file in files:   if file.find(".t2t") != -1:# 查找特定擴(kuò)展名的文件       file_dir_path = os.path.join(root,file)       fileList.append(file_dir_path)  print fileList

 3、列表按列排序(list sort)

如果列表的每個元素都是一個元組(tuple),我們要根據(jù)元組的某列來排序的化,可參考如下方法:

下面例子我們是根據(jù)元組的第2列和第3列數(shù)據(jù)來排序的,而且是倒序(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', 6429600, '0.0')]

 4、列表去重(list uniq)

有時候需要將list中重復(fù)的元素刪除,就要使用如下方法:

>>> 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、字典排序(dict sort)

一般來說,我們都是根據(jù)字典的key來進(jìn)行排序,但是我們?nèi)绻敫鶕?jù)字典的value值來排序,就使用如下方法:

>>> 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、字典,列表,字符串互轉(zhuǎn)

以下是生成數(shù)據(jù)庫連接字符串,從字典轉(zhuǎn)換到字符串。

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

下面的例子,是將字符串轉(zhuǎn)化為字典。

>>> 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、時間對象操作

將時間對象轉(zhuǎn)換成字符串。

>>> import datetime >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")   '2011-01-20 14:05'

時間大小比較。

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

時間差值計算,計算8小時前的時間。

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

將字符串轉(zhuǎn)換成時間對象。

>>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d") >>> type(endtime)   <type 'datetime.datetime'> >>> print endtime   2010-07-01 00:00:00

將從 1970-01-01 00:00:00 UTC 到現(xiàn)在的秒數(shù),格式化輸出。

>>> import time >>> a = 1302153828 >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))   '2011-04-07 13:23:48'

 8、命令行參數(shù)解析(getopt)

通常在編寫一些日運(yùn)維腳本時,需要根據(jù)不同的條件,輸入不同的命令行選項(xiàng)來實(shí)現(xiàn)不同的功能。

在Python中提供了getopt模塊很好的實(shí)現(xiàn)了命令行參數(shù)的解析,下面距離說明。請看如下程序:

#!/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 格式化輸出

9.1、格式化輸出字符串

截取字符串輸出,下面例子將只輸出字符串的前3個字母。

>>> str="abcdefg" >>> print "%.3s" % str   abc

按固定寬度輸出,不足使用空格補(bǔ)全,下面例子輸出寬度為10。

>>> str="abcdefg" >>> print "%10s" % str      abcdefg

截取字符串,按照固定寬度輸出。

>>> str="abcdefg" >>> print "%10.3s" % str          abc

浮點(diǎn)類型數(shù)據(jù)位數(shù)保留。

>>> import fpformat >>> a= 0.0030000000005 >>> b=fpformat.fix(a,6) >>> print b   0.003000

對浮點(diǎn)數(shù)四舍五入,主要使用到round函數(shù)。

>>> 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、進(jìn)制轉(zhuǎn)換

有些時候需要作不同進(jìn)制轉(zhuǎn)換,可以參考下面的例子(%x 十六進(jìn)制,%d 十進(jìn)制,%o 十進(jìn)制)。

>>> num = 10 >>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)   Hex = a,Dec = 10,Oct = 12

 10、Python調(diào)用系統(tǒng)命令或者腳本

使用 os.system() 調(diào)用系統(tǒng)命令 , 程序中無法獲得到輸出和返回值。

>>> import os >>> os.system('ls -l /proc/cpuinfo') >>> os.system("ls -l /proc/cpuinfo")   -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo   0

使用 os.popen() 調(diào)用系統(tǒng)命令, 程序中可以獲得命令輸出,但是不能得到執(zhí)行的返回值。

>>> out = os.popen("ls -l /proc/cpuinfo") >>> print out.read()   -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo

使用 commands.getstatusoutput() 調(diào)用系統(tǒng)命令, 程序中可以獲得命令輸出和執(zhí)行的返回值。

>>> import commands >>> commands.getstatusoutput('ls /bin/ls')   (0, '/bin/ls')

 11、Python 捕獲用戶 Ctrl+C ,Ctrl+D 事件

有些時候,需要在程序中捕獲用戶鍵盤事件,比如ctrl+c退出,這樣可以更好的安全退出程序。

try:     do_some_func() except KeyboardInterrupt:     print "User Press Ctrl+C,Exit" except EOFError:     print "User Press Ctrl+D,Exit"

 12、Python 讀寫文件

一次性讀入文件到列表,速度較快,適用文件比較小的情況下

track_file = "track_stock.conf" fd = open(track_file) content_list = fd.readlines() fd.close() for line in content_list:     print line

逐行讀入,速度較慢,適用沒有足夠內(nèi)存讀取整個文件(文件太大)

fd = open(file_path) fd.seek(0) title = fd.readline() keyword = fd.readline() uuid = fd.readline() fd.close()

寫文件 write 與 writelines 的區(qū)別 。

Fd.write(str) : 把str寫到文件中,write()并不會在str后加上一個換行符。

Fd.writelines(content) : 把content的內(nèi)容全部寫到文件中,原樣寫入,不會在每行后面加上任何東西。

“Python語言常用基礎(chǔ)知識點(diǎn)是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI