python3學(xué)習(xí)筆記

2019年6月5日11:38:50 發(fā)表評論 3,832 ℃

print(‘’):#打印字符串  shell實(shí)現(xiàn)方法:echo

print('hello',end='')

return:返回值

 

input():#獲取鍵盤輸入 shell實(shí)現(xiàn)方法:read

 

len():#獲取字符串長度 shell實(shí)現(xiàn)方法:${#str}

 

str():字符串

int():整數(shù)

float():浮點(diǎn)數(shù)

 

round():浮點(diǎn)數(shù)四舍五入  shell: echo "scale=2;2.34*6.66" | bc

abs():返回?cái)?shù)字的絕對值

 

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ù)可以為序列。

\r : 回車, \n : 換行, \t : 制表符

 

join() 返回通過指定字符連接序列中元素后生成的新字符串。

'-'.join(i for i in "abc")

'a-b-c'

 

pickle 

pickle.dump 將數(shù)據(jù)結(jié)構(gòu)儲(chǔ)存到磁盤

pickle.load 從磁盤獲取數(shù)據(jù)結(jié)構(gòu)

 

pass  占位語句,不作任何輸出

 

Pygame 模塊 游戲開發(fā)模塊

matplotlib 模塊 數(shù)據(jù)可視化模塊

 

random模塊

range(10):生成列表  shell實(shí)現(xiàn)方法:seq 10 或者{1..10}

range(1,10,2) range(10,-5,-1)

 

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

sys.exit : 提前結(jié)束程序 ,shell 實(shí)現(xiàn)方法 :exit

sys.argv : 命令行參數(shù)保存變量

 

列表

a=['cat', 'bat', 'rat', 'elephant']

a[0]  cat

a[1]  bat

shell :

a=(cat bat rat elephant)

${a[0]}  cat

${a[1]}   bat

len() 返回列表長度

del list[#] 刪除列表中的值

list()和tuple() 將列表和元組進(jìn)行轉(zhuǎn)換

 

copy模塊

copy() 復(fù)制列表或字典這樣的可變值

deepcopy() 復(fù)制列表和列表內(nèi)部的列表

 

方法

index() 判斷值是否存在返回下標(biāo)

append() 添加值到列表尾

insert(#,str) 添加到列表指定位置#

remove() 刪除列表值

sort() 將列表中的值排序

list.sort(reverse=True) 逆序排序

list.sort(key=str.lower) 按照普通字典排序

sorted() 將列表進(jìn)行臨時(shí)排序

set() 去除列表重復(fù)的值

reverse() 倒序打印列表

 

字典

keys() 鍵列表

values() 值列表

items() 鍵和值的元組

get(key,key1) 判斷字典如果key不存在,返回key1

del() 刪除鍵和值

 

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

pprint.pprint() 格式化輸出

pprint.pformat() 獲取數(shù)據(jù) 不打印

str = pprint.pformat(count)

函數(shù)

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

訪問屬性:

myDog = dog('litte',6)

myDog.name

myDog.age

調(diào)用方法:

myDog.sit()

myDOg.pollOver()

設(shè)置屬性默認(rèn)值

self.color = 'black'

修改屬性值

myDog.color = 'blue'

通過方法修改屬性值

 

繼承父類

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]

isupper() 判斷字母是否全部為大寫

islower() 判斷字母是否全部為小寫

 

isalpha()返回 True,如果字符串只包含字母,并且非空;

isalnum()返回 True,如果字符串只包含字母和數(shù)字,并且非空;

isdecimal()返回 True,如果字符串只包含數(shù)字字符,并且非空;

isspace()返回 True,如果字符串只包含空格、制表符和換行,并且非空;

istitle()返回True,如果字符串僅包含以大寫字母開頭、后面都是小寫字母的單詞。

 

startswith() 方法返回 True,它所調(diào)用的字符串以該方法傳入的字符串開始

endswith() 方法返回 True,它所調(diào)用的字符串以該方法傳入的字符串結(jié)束

 

join() 將字符串列表鏈接起來

'#'.join(['My', 'name', 'is', 'Simon'])

'My#name#is#Simon'

split() 將字符串分割一個(gè)字符串列表

'My#name#is#Simon'.split('#')

['My', 'name', 'is', 'Simon']

 

rjust(#,str) 右對齊 #表示字符串長度,str表示填寫字符,默認(rèn)空格

ljust(#,) 左對齊

center(#,) 居中對齊

#!/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

lstrip() 刪除左邊的空白字符

rstrip() 刪除右邊的空白字符

 

pyperclip模塊

copy() 向計(jì)算機(jī)剪切板發(fā)送文本

paste() 從計(jì)算機(jī)剪切板粘貼文本

 

正則表達(dá)式

使用步驟

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í)際匹配文本的字符串。

() 括號(hào)分組

(\d\d\d)-(\d\d\d-\d\d\d\d)

正則表達(dá)式字符串中的第一對括號(hào)是第 1 組(str.group(1)),第二對括號(hào)是第 2 組(str.group(2))。

傳入0或者不傳,返回整個(gè)匹配文本。

groups() 返回所有分組

| 匹配多個(gè)分組

>>> batRegex = re.compile(r'Bat(man|mobile|copter|bat)')

>>> mo = batRegex.search('Batmobile lost a wheel')

>>> mo.group()

'Batmobile'

>>> mo.group(1)

'mobile'

?可選匹配 ,匹配這個(gè)問號(hào)之前的分組0次或1次

第二種含義:聲明非貪心匹配 Python默認(rèn)為貪心模式,匹配最長字符串  花括號(hào)的“非貪心”版本匹配盡可能最短的字符串,即在結(jié)束的花括號(hào)后跟著一個(gè)問號(hào)(ha){3,5}? 匹配最小字符串

*   匹配這個(gè)星號(hào)之前的分組0次或多次

+   匹配這個(gè)+號(hào)之前的分組1次或多次

{}  匹配特定次數(shù)

(Ha){3} 匹配3次或者更多次

(Ha){,5}將匹配 0 到 5 次實(shí)例

(Ha){3,5} 將匹配3、4、5次

 

re.compile()

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á)式字符串中的空白符和注釋

search() 返回第一次匹配的文本

findall()  返回所有匹配的字符串列表

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

sub() 替換字符串

第一個(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)

 

字符分類

\d  0 到 9 的任何數(shù)字

\D 除 0 到 9 的數(shù)字以外的任何字符

\w 任何字母、數(shù)字或下劃線字符(可以認(rèn)為是匹配“單詞”字符)

\W 除字母、數(shù)字和下劃線以外的任何字符

\s 空格、制表符或換行符(可以認(rèn)為是匹配“空白”字符)

\S 除空格、制表符和換行符以外的任何字符

 

[a-z] 匹配所有小寫字母

[A-Z] 匹配所有大寫字母

[0-9] 匹配所有數(shù)字

[]:匹配指定訪問內(nèi)的任意單個(gè)字符

[^] 匹配指定字符以外的字符

    ^   行首錨定;用于模式的最左側(cè)

    $   行尾錨定;用于模式的最右側(cè)

.    匹配除了換行之外的所有字符

 re.DOTALL  讓.匹配換行符

re.compile('.*', re.DOTALL)

    .*  配置任意長度的任意字符

 

讀寫文件

OS模塊

os.path

os.path.join() 返回一個(gè)文件路徑的字符串

windows

>>> os.path.join('root','download','test')

'root\\download\\test'

Linux

>>> os.path.join('root','download','test')

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

('/root/python', 'if.py')

os.path.splitext(path) 返回文件名和擴(kuò)展名

os.path.splitext('/tmp/test/1.txt')

('/tmp/test/1', '.txt')

 

endswith() 方法用于判斷字符串是否以指定后綴結(jié)尾,如果以指定后綴結(jié)尾返回True,否則返回False。

str.endswith(suffix[, start[, end]])

>>> 'abcd!!!.txt'.endswith('.txt',7,11)

True

 

os.path.sep  路徑分隔符

 

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.listdir(path)   返回文件名字符串的列表

os.getcwd()  返回當(dāng)前工作目錄

os.chdir() 改變當(dāng)前工作路徑

os.makedirs() 創(chuàng)建文件夾

os.unlink(path)  刪除 path 處的文件

os.rmdir(path)   將刪除 path 處的文件夾。該文件夾必須為空,其中沒有任何文件和文件夾。

 

os.walk(path)  返回三個(gè)值

1.當(dāng)前文件夾名稱的字符串。

2.當(dāng)前文件夾中子文件夾的字符串的列表。

3.當(dāng)前文件夾中文件的字符串的列表。

 

文件讀寫過程

在 Python 中,讀寫文件有 3 個(gè)步驟:

1.調(diào)用 open()函數(shù),返回一個(gè) File 對象。

open(file,'w') 以寫模式打開文件,覆寫原有的文件

open(file,'a') 以添加模式打開文件

2.調(diào)用 File 對象的 read()或 write()方法。

readlines() 按行讀取,返回字符串列表

write()不會(huì)自己添加換行符

3.調(diào)用 File 對象的 close()方法,關(guān)閉該文件。

 

with as

>>>with open("/tmp/foo.txt") as file:

data = file.read()

 

shelve模塊

可以將 Python 程序中的變量保存到二進(jìn)制的 shelf 文件中。

shelve.open() 傳入文件名,將返回的值保存在一個(gè)變量中。

var.close() 關(guān)閉調(diào)用

 

pprint.pformat() 保存變量

>>> import pprint

>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]

>>> pprint.pformat(cats)

"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"

>>> fileObj = open('myCats.py', 'w')

>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')

83

>>> fileObj.close()

 

shutil模塊

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.send2trash()   將文件和文件夾刪除到回收站

 

zipfile模塊

ZipFile

zipfile.ZipFile()  調(diào)用zip對象,第二個(gè)參數(shù)‘w’ ,以寫模式打開 'a' 添加模式打開。

namelist()  返回 ZIP 文件中包含的所有文件和文件夾的字符串的列表。

>>> a=zipfile.ZipFile('test.zip')

>>> a.namelist()

['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 對象

 file_size  原來文件大小

 compress_size  壓縮后文件大小

>>>b= a.getinfo('test/6.txt')

>>> b.file_size

28

>>> b.compress_size

17

>>>a.close()

 

extractall()  從 ZIP 文件中解壓縮所有文件和文件夾,放到當(dāng)前工作目錄中。

extract() 從 ZIP 文件中解壓縮單個(gè)文件到當(dāng)前目錄或指定目錄

 

write() 第一個(gè)參數(shù)是一個(gè)字符串,代表要添加的文件名。第二個(gè)參數(shù)是“壓縮類型”參數(shù),它告訴計(jì)算機(jī)使用怎樣的算法來壓縮文件 compress_type=zipfile.ZIP_DEFLATED。

 

調(diào)試

try:

except (as err)異常處理

 

try:

except:

else:

沒有發(fā)生異常執(zhí)行此處代碼

 

try:

finally:

 

raise Exception() 拋出異常

 

traceback 模塊

traceback.format_exc() 得到反向跟蹤字符串

 

斷言

assert 關(guān)鍵字  條件, 當(dāng)條件為False時(shí)顯示的字符串

 

日志

import logging

logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')

 

#將日志寫入文件

import logging

logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

 

loggin.disable(logging.CRITICAL) 禁止日志

 

日志級(jí)別

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)致程序完全停止工作

 

unittest 模塊

測試函數(shù)

測試類

 

json模塊處理json數(shù)據(jù)

json.loads() 讀取json

json.dumps() 寫出json

 

time 模塊

time.time()  當(dāng)前時(shí)間

time.sleep(#) 暫停時(shí)間#秒

 

datetime模塊

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)

>>> today + aboutYears

datetime.datetime(2037, 5, 8, 14, 35, 3, 697342)

>>> aboutYears.total_seconds()

567648000.0

 

暫停直至特定日期

import datetime

import time

halloween = datetime.datetime(2019, 10, 31, 0, 0, 0)

while datetime.datetime.now() < halloween:

time.sleep(1)

 

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

'2019-05-13 14:49:46'

>>> datetime.datetime.strptime('05, 21, 2019', '%m, %d, %Y')

datetime.datetime(2019, 5, 21, 0, 0)

python3學(xué)習(xí)筆記

threading  多線程模塊

 threading.Thread()     創(chuàng)建新的線程

start() 執(zhí)行線程

#!/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 ')

執(zhí)行結(jié)果:

start

End

wake up

 

向線程的目標(biāo)函數(shù)傳遞參數(shù)

>>> threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '})

>>> threadObj.start()

Cats & Dogs & Frogs

 

subprocess 模塊

打開計(jì)算器其他程序

window :

>>>subprocess.Popen('C:\\Windows\\System32\\calc.exe')

llinux:

>>> subprocess.Popen('/usr/bin/top')

poll() 是否已經(jīng)執(zhí)行完代碼

返回None 表示仍在運(yùn)行

返回0 正常退出

返回1 錯(cuò)誤導(dǎo)致退出

wait() 等待執(zhí)行完代碼以后,再執(zhí)行其他代碼

Popen() 傳遞命令行參數(shù)

>>>subprocess.Popen(['C:\\Windows\\notepad.exe', 'C:\\hello.txt'])

>>> subprocess.Popen(['C:\\python34\\python.exe', 'hello.py'])

 

用默認(rèn)的程序打開文件

Windows     start

OS X        open

Ubuntu Linux  see

>>>subprocess.Popen(['start', 'hello.txt'], shell=True)

 

smtplib 模塊

連接到SMTP服務(wù)器

smtplib.SMTP()

smtplib.SMTP_SSL()

ehlo()   與smtp服務(wù)器簡歷連接

starttls()  讓SMTP連接處于TLS模式,使用SSL,忽略

login() ('mail@mail.com','password') 登錄smtp服務(wù)器

sendmail() 發(fā)送電子郵件

sendmail()方法需要三個(gè)參數(shù):

你的電子郵件地址字符串(電子郵件的“from”地址)。

收件人的電子郵件地址字符串,或多個(gè)收件人的字符串列表(作為“to”地址)。

電子郵件正文字符串。

電子郵件正文字符串必須以'Subject: \n'開頭,作為電子郵件的主題行。'\n'換行

 

>>> import smtplib

>>> from email.mime.text import MIMEText

>>> msg = MIMEText('my name is python')

>>> msg['Subject']='Python Email'

>>> msg['From']='xxxx@163.com'

>>> msg['To']='xxxx@qq.com'

>>> s= smtplib.SMTP('smtp.163.com')

>>> s.ehlo()

>>> s.login('xxxx@163.com','xxxxxx')

(235, b'Authentication successful')

>>> s.send_message(msg)

{}

>>> s.quit()

 

 

imaplib imapclient pyzmail模塊

郵件接收模塊

pip install imapclient

pip install pyzmail36

 

Pillow 模塊 圖像處理

pip install pillow

from PIL import ImageColor

 ImageColor.getcolor()  返回RGBA元組

>>> ImageColor.getcolor('red', 'RGBA')

(255, 0, 0, 255)

>>> ImageColor.getcolor('green', 'RGBA')

(0, 128, 0, 255)

 

 Image.open()操作圖像

>>> from PIL import Image

>>> catImg = Image.open('2.jpg')

>>> catImg.size

(256, 348)

>>> w,h = catImg.size

>>> w

256

>>> h

348

>>> catImg.filename

'2.jpg'

>>> catImg.format

'JPEG'

>>> catImg.format_description

'JPEG (ISO 10918)'

>>> catImg.save('3.png')

 

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

 

crop()裁剪圖片

>>> cropImg = catImg.crop((100,110,230,300))

>>> cropImg.save('2-2.jpg')

 

copy()復(fù)制圖片

paste()粘貼圖片

>>> imgLog = Image.open('log.png')

>>> catCopyimg = catImg.copy()

>>> catCopyimg.paste(imgLog,(156,248))

>>> catCopyimg.paste(imgLog,(156,248),imgLog) #粘貼透明圖像

>>> catCopyimg.sava('3.png')

 

resize()調(diào)整圖像大小

>>>w,h = catImg.size

>>> newImg = catImg.resize((int(w/2),int(h/2)))

>>> newImg.save('4.jpg')

 

rotate()旋轉(zhuǎn)圖像

旋轉(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()       翻轉(zhuǎn)圖像

必須向 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.getpixel((0, 0))

(0, 0, 0, 0)

>>> for x in range(100):

for y in range(50):

im.putpixel((x,y),(110,110,110))

>>> for x in range(100):

for y in range(50,100):

im.putpixel((x,y),ImageColor.getcolor('red','RGBA'))

>>> im.getpixel((0, 0))

(210, 210, 210, 255)

>>> im.getpixel((0, 50))

(255, 0, 0, 255)

>>> im.save('test.png')

 

在圖像上繪畫

from PIL import Image, ImageDraw

點(diǎn)

point(xy, fill)

line(xy, fill, width)

矩形

rectangle(xy, fill, outline)

橢圓

ellipse(xy, fill, outline)

多邊形

polygon(xy, fill, outline)

 

>>> from PIL import Image, ImageDraw

>>> im = Image.new('RGBA', (200, 200), 'white')

>>> draw = ImageDraw.Draw(im)

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

>>> im.save('123.png')

 

text()繪制文本

4 個(gè)參數(shù):xy、text、fill 和 font。

xy 參數(shù)是兩個(gè)整數(shù)的元組,指定文本區(qū)域的左上角。

text 參數(shù)是想寫入的文本字符串。

可選參數(shù) fill 是文本的顏色。

可選參數(shù) font 是一個(gè) ImageFont 對象,用于設(shè)置文本的字體和大小。

from PIL import ImageFont

ImageFont.truetype()

第一個(gè)參數(shù)是字符串,表示字體的TrueType 文件,這是硬盤上實(shí)際的字體文件。TrueType 字體文件具有.TTF 文件擴(kuò)展名,通??梢栽谝韵挛募A中找到:

在 Windows 上:C:\Windows\Fonts。

在 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

>>> import os

>>> im = Image.new('RGBA', (200, 200), 'white')

>>> draw = ImageDraw.Draw(im)

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

>>> im.save('text.png')

 

textsize()測量文本字符串

 

pyautogui模塊

windows

pip install PyGetWindow==0.0.1

pip install pyautogui

 

pyautogui. FAILSAFE = False  禁止自動(dòng)防故障功能

pyautogui.PAUSE = 1 每次pyautogui函數(shù)調(diào)用后暫停一秒

pyautogui.size()獲取屏幕分辨率

 

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)

 

pyautogui.screenshot()獲取屏幕快照

getpixel()  傳入坐標(biāo)元組,返回坐標(biāo)處的像素顏色

pixelMatchesColor()     如果屏幕上指定的 x、y 坐標(biāo)處的像素與指定的顏色匹配,返回true

>>> im.getpixel((50, 200))

(245, 245, 245)

>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 245))

True

>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 246))

False

pyautogui.locateOnScreen()

函數(shù)返回4個(gè)整數(shù)的元組,是屏幕上首次發(fā)現(xiàn)該圖像時(shí)左邊的x 坐標(biāo)、頂邊的 y 坐標(biāo)、寬度以及高度。

找不到圖像,返回None

有多處,返回一個(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))

Point(x=43, y=144)

 

pyautogui.typewrite(‘str’,#)  向計(jì)算機(jī)發(fā)送虛擬按鍵,第二個(gè)參數(shù)暫停時(shí)間

>>> pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y'])

XYab

pyautogui.KEYBOARD_KEYS 查看鍵盤鍵字符串

python3學(xué)習(xí)筆記

python3學(xué)習(xí)筆記

 

pyautogui.press()模擬擊鍵

pyautogui.hotkey()組合按鍵

pyautogui.hotkey('ctrl', 'c')

 

【騰訊云】云服務(wù)器、云數(shù)據(jù)庫、COS、CDN、短信等云產(chǎn)品特惠熱賣中

發(fā)表評論

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: