print(‘’):#打印字符串 shell實(shí)現(xiàn)方法:echo
input():#獲取鍵盤輸入 shell實(shí)現(xiàn)方法:read
len():#獲取字符串長度 shell實(shí)現(xiàn)方法:${#str}
round():浮點(diǎn)數(shù)四舍五入 shell: echo "scale=2;2.34*6.66" | bc
break:退出循環(huán) ,shell實(shí)現(xiàn)方法一樣
continue:退出當(dāng)前循環(huán),進(jìn)入下一路新的循環(huán),shell實(shí)現(xiàn)方法一樣
str.isdigit() 檢測字符串是否只由數(shù)字組成
max( x, y, z, .... ) 返回給定參數(shù)的最大值,參數(shù)可以為序列。
join() 返回通過指定字符連接序列中元素后生成的新字符串。
pickle.dump 將數(shù)據(jù)結(jié)構(gòu)儲(chǔ)存到磁盤
pickle.load 從磁盤獲取數(shù)據(jù)結(jié)構(gòu)
matplotlib 模塊 數(shù)據(jù)可視化模塊
range(10):生成列表 shell實(shí)現(xiàn)方法:seq 10 或者{1..10}
random.randint(a,b) #import random生成隨機(jī)數(shù);shell實(shí)現(xiàn)方法 $(($RANDOM%50+1))
random.sample(list,#) 從list隨機(jī)獲取#個(gè)元素
random.shuffle(list) 將序列隨機(jī)排序
randdom.choice() 從列表隨機(jī)選一個(gè)項(xiàng)
random.seed(datetime.datetime.now()) 隨機(jī)數(shù)種子
sys.exit : 提前結(jié)束程序 ,shell 實(shí)現(xiàn)方法 :exit
a=['cat', 'bat', 'rat', 'elephant']
list()和tuple() 將列表和元組進(jìn)行轉(zhuǎn)換
deepcopy() 復(fù)制列表和列表內(nèi)部的列表
list.sort(key=str.lower) 按照普通字典排序
get(key,key1) 判斷字典如果key不存在,返回key1
setdefault(key,key1) 為鍵設(shè)置一個(gè)默認(rèn)值
#!/usr/bin/python36 import pprint message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for m in message: count.setdefault(m,0) count[m] = count[m] +1 pprint.pprint(count)
pprint.pformat() 獲取數(shù)據(jù) 不打印
from module_name import function_name 導(dǎo)入模塊中指定函數(shù)
from module_name import function_name as fn 指定fn別名
class dog(): def __init__(self,name,age): """初始化屬性name和age""" self.name = name self.age = age def sit(self): print(self.name.title() + ' is now sitting.') ##self.name.title() 首字母大寫 def rollOver(self): print(self>name.title() + 'rolled over!')
class ElectricCar(Car): def __init__(self, make, model, year): """初始化父類的屬性""" super().__init__(make, model, year) self.batterySize = 70 self.battery = Battery() #將實(shí)例用作屬性,Battery()類的實(shí)例為 ElectricCar類的一個(gè)屬性
super() 是一個(gè)特殊函數(shù),幫助Python將父類和子類關(guān)聯(lián)起來。這行代碼讓Python調(diào)用ElectricCar 的父類的方法 __init__() ,讓 ElectricCar 實(shí)例包含父類的所有屬性。
upper() 全部字母轉(zhuǎn)換為大寫 shell:tr [a-z] [A-Z]
lower() 全部字符轉(zhuǎn)換為小寫 shell: tr [A-Z] [a-z]
isalpha()返回 True,如果字符串只包含字母,并且非空;
isalnum()返回 True,如果字符串只包含字母和數(shù)字,并且非空;
isdecimal()返回 True,如果字符串只包含數(shù)字字符,并且非空;
isspace()返回 True,如果字符串只包含空格、制表符和換行,并且非空;
istitle()返回True,如果字符串僅包含以大寫字母開頭、后面都是小寫字母的單詞。
startswith() 方法返回 True,它所調(diào)用的字符串以該方法傳入的字符串開始
endswith() 方法返回 True,它所調(diào)用的字符串以該方法傳入的字符串結(jié)束
'#'.join(['My', 'name', 'is', 'Simon'])
rjust(#,str) 右對齊 #表示字符串長度,str表示填寫字符,默認(rèn)空格
#!/usr/bin/python36 def Pic(Dict,lw,rw): print('PICNIC ITEMS'.center(lw + rw ,'-')) for m,n in Dict.items(): print(m.ljust(lw,'.') + str(n).rjust(rw)) picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} Pic(picnicItems,10,5)
strip(str) 刪除開頭和末尾的空白字符 ,str表示刪除指定的字符 Abcd :表示刪除出現(xiàn)的A、b、c、d
copy() 向計(jì)算機(jī)剪切板發(fā)送文本
1.用 import re 導(dǎo)入正則表達(dá)式模塊。
2.用 re.compile()函數(shù)創(chuàng)建一個(gè) Regex 對象(記得使用原始字符串)。
3.向 Regex 對象的 search()方法傳入想查找的字符串。它返回一個(gè) Match 對象。
4.調(diào)用 Match 對象的 group()方法,返回實(shí)際匹配文本的字符串。
正則表達(dá)式字符串中的第一對括號(hào)是第 1 組(str.group(1)),第二對括號(hào)是第 2 組(str.group(2))。
>>> batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
>>> mo = batRegex.search('Batmobile lost a wheel')
?可選匹配 ,匹配這個(gè)問號(hào)之前的分組0次或1次
第二種含義:聲明非貪心匹配 Python默認(rèn)為貪心模式,匹配最長字符串 花括號(hào)的“非貪心”版本匹配盡可能最短的字符串,即在結(jié)束的花括號(hào)后跟著一個(gè)問號(hào)(ha){3,5}? 匹配最小字符串
re.compile(r'[a-z]',re.I) 不區(qū)分大小寫
re.compile('.*', re.DOTALL) 讓.匹配換行符
re.compile('foo', re.IGNORECASE | re.DOTALL) 不區(qū)分大小寫,并且句點(diǎn)字符匹配換行符
re.compile('',re.VERBOSE) 忽略正則表達(dá)式字符串中的空白符和注釋
1.如果調(diào)用在一個(gè)沒有分組的正則表達(dá)式上,例如\d\d\d-\d\d\d-\d\d\d\d,方法findall()將返回一個(gè)匹配字符串的列表,例如['415-555-9999', '212-555-0000']。
2.如果調(diào)用在一個(gè)有分組的正則表達(dá)式上,例如(\d\d\d)-(\d\d\d)-(\d\d\d\d),方法 findall()將返回一個(gè)字符串的元組的列表(每個(gè)分組對應(yīng)一個(gè)字符串),例如[('415','555', '1122'), ('212', '555', '0000')]
第一個(gè)參數(shù)是一個(gè)字符串,用于取代發(fā)現(xiàn)的匹配。第二個(gè)參數(shù)是一個(gè)字符串,即正則表達(dá)式。第三個(gè)參數(shù)是替換次數(shù),默認(rèn)為0 全部替換。
sub()的第一個(gè)參數(shù)中,可以輸入\1、\2、\3……。表示“在替換中輸入分組 1、2、3……的文本
>>> namesRegex = re.compile(r'Agent \w+')
>>> namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
'CENSORED gave the secret documents to CENSORED.'
>>>b= re.sub('\n+', " ", content)
\w 任何字母、數(shù)字或下劃線字符(可以認(rèn)為是匹配“單詞”字符)
\s 空格、制表符或換行符(可以認(rèn)為是匹配“空白”字符)
os.path.join() 返回一個(gè)文件路徑的字符串
>>> os.path.join('root','download','test')
>>> os.path.join('root','download','test')
os.path.abspath(path) 返回參數(shù)的絕對路徑的字符串
os.path.isabs(path) 參數(shù)是一個(gè)絕對路徑返回True ,否則返回False
os.path.relpath(paht,start) 返回從 start 路徑到 path 的相對路徑的字符串
os.path.dirname(path) 返回參數(shù)中最后一個(gè)斜杠之前的所有內(nèi)容(目錄名稱)
os.path.basename(path) 返回參數(shù)中最后一個(gè)斜杠之后的所有內(nèi)容 (文件名稱)
os.path.split(path) 返回 目錄名稱和基本文件 的字符串元組
>>> os.path.split('/root/python/if.py')
os.path.splitext(path) 返回文件名和擴(kuò)展名
os.path.splitext('/tmp/test/1.txt')
endswith() 方法用于判斷字符串是否以指定后綴結(jié)尾,如果以指定后綴結(jié)尾返回True,否則返回False。
str.endswith(suffix[, start[, end]])
>>> 'abcd!!!.txt'.endswith('.txt',7,11)
os.path.getsize(path) 返回 path 參數(shù)中文件的字節(jié)數(shù)
os.path.exists(path) 如果 path 參數(shù)所指的文件或文件夾存在,返回True
os.path.isfile(path) 如果 path 參數(shù)存在,并且是一個(gè)文件,返回True
os.path.isdir(path) 如果 path 參數(shù)存在,并且是一個(gè)文件夾,返回True
os.rmdir(path) 將刪除 path 處的文件夾。該文件夾必須為空,其中沒有任何文件和文件夾。
1.調(diào)用 open()函數(shù),返回一個(gè) File 對象。
open(file,'w') 以寫模式打開文件,覆寫原有的文件
2.調(diào)用 File 對象的 read()或 write()方法。
3.調(diào)用 File 對象的 close()方法,關(guān)閉該文件。
>>>with open("/tmp/foo.txt") as file:
可以將 Python 程序中的變量保存到二進(jìn)制的 shelf 文件中。
shelve.open() 傳入文件名,將返回的值保存在一個(gè)變量中。
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
shutil.copy(source,destination) 將路徑source 處的文件復(fù)制到路徑destination處的文件夾(source 和 destination 都是字符串)
shutil.copytree(source, destination) 將路徑 source 處的文件夾,包括它的所有文件和子文件夾,復(fù)制到路徑 destination 處的文件夾
shutil.move(source, destination),將路徑 source 處的文件夾移動(dòng)到路徑destination,并返回新位置的絕對路徑的字符串。
shutil.rmtree(path) 將刪除 path 處的文件夾,它包含的所有文件和文件夾都會(huì)被刪除。
send2trash.send2trash() 將文件和文件夾刪除到回收站
zipfile.ZipFile() 調(diào)用zip對象,第二個(gè)參數(shù)‘w’ ,以寫模式打開 'a' 添加模式打開。
namelist() 返回 ZIP 文件中包含的所有文件和文件夾的字符串的列表。
>>> a=zipfile.ZipFile('test.zip')
['test/', 'test/1/', 'test/1/2/', 'test/1/2/3/', 'test/1.txt', 'test/2.txt', 'test/3.txt', 'test/4.txt', 'test/5.txt', 'test/6.txt']
getinfo() 返回一個(gè)關(guān)于特定文件的 ZipInfo 對象
extractall() 從 ZIP 文件中解壓縮所有文件和文件夾,放到當(dāng)前工作目錄中。
extract() 從 ZIP 文件中解壓縮單個(gè)文件到當(dāng)前目錄或指定目錄
write() 第一個(gè)參數(shù)是一個(gè)字符串,代表要添加的文件名。第二個(gè)參數(shù)是“壓縮類型”參數(shù),它告訴計(jì)算機(jī)使用怎樣的算法來壓縮文件 compress_type=zipfile.ZIP_DEFLATED。
traceback.format_exc() 得到反向跟蹤字符串
assert 關(guān)鍵字 條件, 當(dāng)條件為False時(shí)顯示的字符串
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
loggin.disable(logging.CRITICAL) 禁止日志
DEBUG logging.debug() 最低級(jí)別。用于小細(xì)節(jié)。通常只有在診斷問題時(shí),你才會(huì)關(guān)心這些消息
INFO logging.info() 用于記錄程序中一般事件的信息,或確認(rèn)一切工作正常
WARNING logging.warning() 用于表示可能的問題,它不會(huì)阻止程序的工作,但將來可能會(huì)
ERROR logging.error() 用于記錄錯(cuò)誤,它導(dǎo)致程序做某事失敗
CRITICAL logging.critical() 最高級(jí)別。用于表示致命的錯(cuò)誤,它導(dǎo)致或?qū)⒁獙?dǎo)致程序完全停止工作
datetime.datetime.now() 返回當(dāng)前時(shí)間
datetime.datetime.fromtimestamp() Unix 紀(jì)元時(shí)間戳 轉(zhuǎn)換為datetime對象
>>> datetime.datetime.fromtimestamp(1557728114)
datetime.datetime(2019, 5, 13, 14, 15, 14)
datetime.timedelta() 接受關(guān)鍵字參數(shù) weeks、days、hours、minutes、seconds、milliseconds 和 microseconds
total_seconds() 返回知以秒表示的時(shí)間
>>> today = datetime.datetime.now()
>>> aboutYears = datetime.timedelta(days=365*18)
datetime.datetime(2037, 5, 8, 14, 35, 3, 697342)
>>> aboutYears.total_seconds()
halloween = datetime.datetime(2019, 10, 31, 0, 0, 0)
while datetime.datetime.now() < halloween:
strftime() 將datetime對象轉(zhuǎn)換為字符串
strptime(time_string, format) 將字符串轉(zhuǎn)換為datetime;函數(shù)返回一個(gè) datetime 對象,它的時(shí)刻由time_string 指定,利用format 字符串參數(shù)來解析。
>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>>> datetime.datetime.strptime('05, 21, 2019', '%m, %d, %Y')
datetime.datetime(2019, 5, 21, 0, 0)
threading.Thread() 創(chuàng)建新的線程
#!/usr/bin/python36 import threading,time print('start') def takeANap(): time.sleep(5) print('wake up') threadObj = threading.Thread(target=takeANap) threadObj.start() print('End ')
>>> threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '})
>>>subprocess.Popen('C:\\Windows\\System32\\calc.exe')
>>> subprocess.Popen('/usr/bin/top')
wait() 等待執(zhí)行完代碼以后,再執(zhí)行其他代碼
>>>subprocess.Popen(['C:\\Windows\\notepad.exe', 'C:\\hello.txt'])
>>> subprocess.Popen(['C:\\python34\\python.exe', 'hello.py'])
>>>subprocess.Popen(['start', 'hello.txt'], shell=True)
starttls() 讓SMTP連接處于TLS模式,使用SSL,忽略
login() ('mail@mail.com','password') 登錄smtp服務(wù)器
收件人的電子郵件地址字符串,或多個(gè)收件人的字符串列表(作為“to”地址)。
電子郵件正文字符串必須以'Subject: \n'開頭,作為電子郵件的主題行。'\n'換行
>>> from email.mime.text import MIMEText
>>> msg = MIMEText('my name is python')
>>> msg['Subject']='Python Email'
>>> msg['From']='xxxx@163.com'
>>> s= smtplib.SMTP('smtp.163.com')
>>> s.login('xxxx@163.com','xxxxxx')
(235, b'Authentication successful')
ImageColor.getcolor() 返回RGBA元組
>>> ImageColor.getcolor('red', 'RGBA')
>>> ImageColor.getcolor('green', 'RGBA')
>>> catImg = Image.open('2.jpg')
Image.new(‘RGBA’,(#,#),‘顏色’) 返回空白圖像
字符串'RGBA',將顏色模式設(shè)置為 RGBA(還有其他模式)
大小,是兩個(gè)整數(shù)元組,作為新圖像的寬度和高度。
圖像開始采用的背景顏色,是一個(gè)表示 RGBA 值的四整數(shù)元組。你可以用ImageColor.getcolor()函數(shù)的返回值作為這個(gè)參數(shù)。另外,Image.new()也支持傳入標(biāo)準(zhǔn)顏色名稱的字符串。
>>> im = Image.new('RGBA', (100, 200), 'purple')
>>> im.save('purpleImage.png')
>>> im2 = Image.new('RGBA', (20, 20))
>>> im2.save('transparentImage.png')
>>> cropImg = catImg.crop((100,110,230,300))
>>> imgLog = Image.open('log.png')
>>> catCopyimg = catImg.copy()
>>> catCopyimg.paste(imgLog,(156,248))
>>> catCopyimg.paste(imgLog,(156,248),imgLog) #粘貼透明圖像
>>> newImg = catImg.resize((int(w/2),int(h/2)))
旋轉(zhuǎn) 90 度或 270 度時(shí),寬度和高度會(huì)變化,在 Windows 上,使用黑色的背景來填補(bǔ)旋轉(zhuǎn)造成的縫隙,可選expand 關(guān)鍵字參數(shù),如果設(shè)置為 True,就會(huì)放大圖像的尺寸,以適應(yīng)整個(gè)旋轉(zhuǎn)
>>>catImg.rotate(90).save('90.png')
>>> catImg.rotate(90,expand=True).save('901.png')
必須向 transpose()方法傳入 Image.FLIP_LEFT_RIGHT 或 Image.FLIP_TOP_BOTTOM
>>> catImg.transpose(Image.FLIP_LEFT_RIGHT).save('xuanzhuan.jpg')
>>> catImg.transpose(Image.FLIP_TOP_BOTTOM).save('xuanzhuan.jpg')
getpixel() 和 putpixel() 更改單個(gè)像素
>>> im = Image.new('RGBA', (100, 100))
im.putpixel((x,y),(110,110,110))
im.putpixel((x,y),ImageColor.getcolor('red','RGBA'))
from PIL import Image, ImageDraw
>>> from PIL import Image, ImageDraw
>>> im = Image.new('RGBA', (200, 200), 'white')
>>> draw.line([(0, 0), (199, 0), (199, 199), (0, 199), (0, 0)], fill='black')
>>> draw.rectangle((20, 30, 60, 60), fill='blue')
>>> draw.ellipse((120, 30, 160, 60), fill='red')
>>> draw.polygon(((57, 87), (79, 62), (94, 85), (120, 90), (103, 113)),fill='brown')
>>> for i in range(100, 200, 10):
draw.line([(i, 0), (200, i - 100)], fill='green')
4 個(gè)參數(shù):xy、text、fill 和 font。
xy 參數(shù)是兩個(gè)整數(shù)的元組,指定文本區(qū)域的左上角。
可選參數(shù) font 是一個(gè) ImageFont 對象,用于設(shè)置文本的字體和大小。
第一個(gè)參數(shù)是字符串,表示字體的TrueType 文件,這是硬盤上實(shí)際的字體文件。TrueType 字體文件具有.TTF 文件擴(kuò)展名,通??梢栽谝韵挛募A中找到:
在 OS X 上:/Library/Fonts and /System/Library/Fonts。
在 Linux 上:/usr/share/fonts/truetype。
第二個(gè)參數(shù)是一個(gè)整數(shù),表示字體大小的點(diǎn)數(shù)(而不是像素)。請記住,Pillow 創(chuàng)建的PNG 圖像默認(rèn)是每英寸 72 像素,一點(diǎn)是1/72 英寸。
>>> from PIL import Image, ImageDraw, ImageFont
>>> im = Image.new('RGBA', (200, 200), 'white')
>>> draw.text((20, 150), 'Hello', fill='purple')
>>> fontsFolder = 'FONT_ _FOLDER' # e.g. ‘/Library/Fonts’
>>> arialFont = ImageFont.truetype(os.path.join(fontsFolder, 'arial.ttf'), 32)
>>> draw.text((100, 150), 'Howdy', fill='gray', font=arialFont)
pip install PyGetWindow==0.0.1
pyautogui. FAILSAFE = False 禁止自動(dòng)防故障功能
pyautogui.PAUSE = 1 每次pyautogui函數(shù)調(diào)用后暫停一秒
pyautogui.moveTo(x,y,duration) 將鼠標(biāo)立即移動(dòng)到指定位置,duration可選 移動(dòng)所需秒數(shù)
pyautogui.moveRel(x,y,duration) 相對于當(dāng)前位置移動(dòng)鼠標(biāo)x:向右移動(dòng)多少像素 y:向左移動(dòng)多少個(gè)像素
pyautogui.position() 獲取鼠標(biāo)位置
pyautogui.click(x,y,button=) 點(diǎn)擊鼠標(biāo),默認(rèn)點(diǎn)擊左鍵
在當(dāng)前位置以外的其他位置點(diǎn)擊,傳入x,y坐標(biāo), button 關(guān)鍵字參數(shù),值分別為 'left'、'middle'或 'right'
相當(dāng)于pyautogui. mouseDown() 和pyautogui.mouseUp()的封裝
pyautogui.doubleClick()雙擊鼠標(biāo)左鍵
pyautogui.rightClick()雙擊鼠標(biāo)右鍵
pyautogui.middleClick() 雙擊鼠標(biāo)中建
pyautogui.dragTo()按下左鍵移動(dòng)鼠標(biāo)
pyautogui.dragRel()按下左鍵,相對于當(dāng)前位置移動(dòng)鼠標(biāo)
pyautogui.moveTo()將鼠標(biāo)移動(dòng)到指定的x,y坐標(biāo)
pyautogui.moveRel()相對于當(dāng)前位置移動(dòng)鼠標(biāo)
#!python import pyautogui,time time.sleep(5) pyautogui.click() distance = 200 while distance > 0: pyautogui.dragRel(distance,0, duration=0.2) distance -= 5 pyautogui.dragRel(0,distance, duration=0.2) pyautogui.dragRel(-distance,0, duration=0.2) distance -= 5 pyautogui.dragRel(0,-distance, duration=0.2)
pyautogui.scroll(#)滾動(dòng)鼠標(biāo),整數(shù)向上滾動(dòng), 負(fù)數(shù)向下滾動(dòng)
getpixel() 傳入坐標(biāo)元組,返回坐標(biāo)處的像素顏色
pixelMatchesColor() 如果屏幕上指定的 x、y 坐標(biāo)處的像素與指定的顏色匹配,返回true
>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 245))
>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 246))
函數(shù)返回4個(gè)整數(shù)的元組,是屏幕上首次發(fā)現(xiàn)該圖像時(shí)左邊的x 坐標(biāo)、頂邊的 y 坐標(biāo)、寬度以及高度。
有多處,返回一個(gè)Generator,可以傳遞給list(),返回一個(gè)4整數(shù)元組列表。
pyautogui.center()返回圖像中心坐標(biāo)。
>>> pyautogui.locateOnScreen('submit.png')
Box(left=2, top=108, width=83, height=72)
>>> pyautogui.center((2,108,83,72))
pyautogui.typewrite(‘str’,#) 向計(jì)算機(jī)發(fā)送虛擬按鍵,第二個(gè)參數(shù)暫停時(shí)間
>>> pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y'])
pyautogui.KEYBOARD_KEYS 查看鍵盤鍵字符串