python3學習筆記

2019年6月5日11:38:50 發表評論 4,106 ℃

print(‘’):#打印字符串  shell實現方法:echo

print('hello',end='')

return:返回值

 

input():#獲取鍵盤輸入 shell實現方法:read

 

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

 

str():字符串

int():整數

float():浮點數

 

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

abs():返回數字的絕對值

 

break:退出循環 ,shell實現方法一樣

continue:退出當前循環,進入下一路新的循環,shell實現方法一樣

 

str.isdigit() 檢測字符串是否只由數字組成

max( x, y, z, .... ) 返回給定參數的最大值,參數可以為序列。

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

 

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

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

'a-b-c'

 

pickle 

pickle.dump 將數據結構儲存到磁盤

pickle.load 從磁盤獲取數據結構

 

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

 

Pygame 模塊 游戲開發模塊

matplotlib 模塊 數據可視化模塊

 

random模塊

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

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

 

random.randint(a,b) #import random生成隨機數;shell實現方法 $(($RANDOM%50+1))

random.sample(list,#) 從list隨機獲取#個元素

random.shuffle(list) 將序列隨機排序

randdom.choice() 從列表隨機選一個項

random.seed(datetime.datetime.now())    隨機數種子

 

sys模塊

sys.exit : 提前結束程序 ,shell 實現方法 :exit

sys.argv : 命令行參數保存變量

 

列表

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() 將列表和元組進行轉換

 

copy模塊

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

deepcopy() 復制列表和列表內部的列表

 

方法

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

append() 添加值到列表尾

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

remove() 刪除列表值

sort() 將列表中的值排序

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

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

sorted() 將列表進行臨時排序

set() 去除列表重復的值

reverse() 倒序打印列表

 

字典

keys() 鍵列表

values() 值列表

items() 鍵和值的元組

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

del() 刪除鍵和值

 

setdefault(key,key1) 為鍵設置一個默認值

#!/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() 獲取數據 不打印

str = pprint.pformat(count)

函數

from  module_name import  function_name 導入模塊中指定函數

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

調用方法:

myDog.sit()

myDOg.pollOver()

設置屬性默認值

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()  #將實例用作屬性,Battery()類的實例為 ElectricCar類的一個屬性

super() 是一個特殊函數,幫助Python將父類和子類關聯起來。這行代碼讓Python調用ElectricCar 的父類的方法 __init__() ,讓 ElectricCar 實例包含父類的所有屬性。

 

字符串操作

upper() 全部字母轉換為大寫 shell:tr [a-z] [A-Z]

lower() 全部字符轉換為小寫 shell: tr [A-Z] [a-z]

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

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

 

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

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

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

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

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

 

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

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

 

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

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

'My#name#is#Simon'

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

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

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

 

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

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 :表示刪除出現的A、b、c、d

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

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

 

pyperclip模塊

copy() 向計算機剪切板發送文本

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

 

正則表達式

使用步驟

1.用 import re 導入正則表達式模塊。

2.用 re.compile()函數創建一個 Regex 對象(記得使用原始字符串)。

3.向 Regex 對象的 search()方法傳入想查找的字符串。它返回一個 Match 對象。

4.調用 Match 對象的 group()方法,返回實際匹配文本的字符串。

() 括號分組

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

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

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

groups() 返回所有分組

| 匹配多個分組

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

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

>>> mo.group()

'Batmobile'

>>> mo.group(1)

'mobile'

?可選匹配 ,匹配這個問號之前的分組0次或1次

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

*   匹配這個星號之前的分組0次或多次

+   匹配這個+號之前的分組1次或多次

{}  匹配特定次數

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

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

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

 

re.compile()

re.compile(r'[a-z]',re.I) 不區分大小寫

re.compile('.*', re.DOTALL讓.匹配換行符

re.compile('foo', re.IGNORECASE | re.DOTALL) 不區分大小寫,并且句點字符匹配換行符

re.compile('',re.VERBOSE) 忽略正則表達式字符串中的空白符和注釋

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

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

1.如果調用在一個沒有分組的正則表達式上,例如\d\d\d-\d\d\d-\d\d\d\d,方法findall()將返回一個匹配字符串的列表,例如['415-555-9999', '212-555-0000']。

2.如果調用在一個有分組的正則表達式上,例如(\d\d\d)-(\d\d\d)-(\d\d\d\d),方法 findall()將返回一個字符串的元組的列表(每個分組對應一個字符串),例如[('415','555', '1122'), ('212', '555', '0000')]

sub() 替換字符串

第一個參數是一個字符串,用于取代發現的匹配。第二個參數是一個字符串,即正則表達式。第三個參數是替換次數,默認為0 全部替換。

sub()的第一個參數中,可以輸入\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 的任何數字

\D 除 0 到 9 的數字以外的任何字符

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

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

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

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

 

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

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

[0-9] 匹配所有數字

[]:匹配指定訪問內的任意單個字符

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

    ^   行首錨定;用于模式的最左側

    $   行尾錨定;用于模式的最右側

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

 re.DOTALL  讓.匹配換行符

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

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

 

讀寫文件

OS模塊

os.path

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

windows

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

'root\\download\\test'

Linux

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

'root/download/test'

os.path.abspath(path)  返回參數的絕對路徑的字符串

os.path.isabs(path)  參數是一個絕對路徑返回True ,否則返回False

os.path.relpath(paht,start)  返回從 start 路徑到 path 的相對路徑的字符串

 

os.path.dirname(path)  返回參數中最后一個斜杠之前的所有內容(目錄名稱)

os.path.basename(path)   返回參數中最后一個斜杠之后的所有內容 (文件名稱)

os.path.split(path)  返回 目錄名稱和基本文件 的字符串元組

>>> os.path.split('/root/python/if.py')

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

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

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

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

 

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

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

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

True

 

os.path.sep  路徑分隔符

 

os.path.getsize(path)  返回 path 參數中文件的字節數

 

os.path.exists(path)  如果 path 參數所指的文件或文件夾存在,返回True

os.path.isfile(path)  如果 path 參數存在,并且是一個文件,返回True

os.path.isdir(path)  如果 path 參數存在,并且是一個文件夾,返回True

 

os.listdir(path)   返回文件名字符串的列表

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

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

os.makedirs() 創建文件夾

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

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

 

os.walk(path)  返回三個值

1.當前文件夾名稱的字符串。

2.當前文件夾中子文件夾的字符串的列表。

3.當前文件夾中文件的字符串的列表。

 

文件讀寫過程

在 Python 中,讀寫文件有 3 個步驟:

1.調用 open()函數,返回一個 File 對象。

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

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

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

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

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

3.調用 File 對象的 close()方法,關閉該文件。

 

with as

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

data = file.read()

 

shelve模塊

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

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

var.close() 關閉調用

 

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 處的文件復制到路徑destination處的文件夾(source 和 destination 都是字符串)

shutil.copytree(source, destination)  將路徑 source 處的文件夾,包括它的所有文件和子文件夾,復制到路徑 destination 處的文件夾

shutil.move(source, destination),將路徑 source 處的文件夾移動到路徑destination,并返回新位置的絕對路徑的字符串。

shutil.rmtree(path) 將刪除 path 處的文件夾,它包含的所有文件和文件夾都會被刪除。

 

send2trash 模塊(需要安裝)

 send2trash.send2trash()   將文件和文件夾刪除到回收站

 

zipfile模塊

ZipFile

zipfile.ZipFile()  調用zip對象,第二個參數‘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() 返回一個關于特定文件的 ZipInfo 對象

 file_size  原來文件大小

 compress_size  壓縮后文件大小

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

>>> b.file_size

28

>>> b.compress_size

17

>>>a.close()

 

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

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

 

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

 

調試

try:

except (as err)異常處理

 

try:

except:

else:

沒有發生異常執行此處代碼

 

try:

finally:

 

raise Exception() 拋出異常

 

traceback 模塊

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

 

斷言

assert 關鍵字  條件, 當條件為False時顯示的字符串

 

日志

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) 禁止日志

 

日志級別

DEBUG  logging.debug()  最低級別。用于小細節。通常只有在診斷問題時,你才會關心這些消息

INFO  logging.info()  用于記錄程序中一般事件的信息,或確認一切工作正常

WARNING  logging.warning()  用于表示可能的問題,它不會阻止程序的工作,但將來可能會

ERROR  logging.error()  用于記錄錯誤,它導致程序做某事失敗

CRITICAL  logging.critical()  最高級別。用于表示致命的錯誤,它導致或將要導致程序完全停止工作

 

unittest 模塊

測試函數

測試類

 

json模塊處理json數據

json.loads() 讀取json

json.dumps() 寫出json

 

time 模塊

time.time()  當前時間

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

 

datetime模塊

datetime.datetime.now() 返回當前時間

datetime.datetime.fromtimestamp() Unix 紀元時間戳 轉換為datetime對象

>>> datetime.datetime.fromtimestamp(1557728114)

datetime.datetime(2019, 5, 13, 14, 15, 14)

datetime.timedelta()  接受關鍵字參數 weeks、days、hours、minutes、seconds、milliseconds 和 microseconds

total_seconds() 返回知以秒表示的時間

>>> 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對象轉換為字符串

strptime(time_string, format) 將字符串轉換為datetime;函數返回一個 datetime 對象,它的時刻由time_string 指定,利用format 字符串參數來解析。

>>> 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學習筆記

threading  多線程模塊

 threading.Thread()     創建新的線程

start() 執行線程

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

執行結果:

start

End

wake up

 

向線程的目標函數傳遞參數

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

>>> threadObj.start()

Cats & Dogs & Frogs

 

subprocess 模塊

打開計算器其他程序

window :

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

llinux:

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

poll() 是否已經執行完代碼

返回None 表示仍在運行

返回0 正常退出

返回1 錯誤導致退出

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

Popen() 傳遞命令行參數

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

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

 

用默認的程序打開文件

Windows     start

OS X        open

Ubuntu Linux  see

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

 

smtplib 模塊

連接到SMTP服務器

smtplib.SMTP()

smtplib.SMTP_SSL()

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

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

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

sendmail() 發送電子郵件

sendmail()方法需要三個參數:

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

收件人的電子郵件地址字符串,或多個收件人的字符串列表(作為“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',將顏色模式設置為 RGBA(還有其他模式)

大小,是兩個整數元組,作為新圖像的寬度和高度。

圖像開始采用的背景顏色,是一個表示 RGBA 值的四整數元組。你可以用ImageColor.getcolor()函數的返回值作為這個參數。另外,Image.new()也支持傳入標準顏色名稱的字符串。

>>> 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()復制圖片

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()調整圖像大小

>>>w,h = catImg.size

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

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

 

rotate()旋轉圖像

旋轉 90 度或 270 度時,寬度和高度會變化,在 Windows 上,使用黑色的背景來填補旋轉造成的縫隙,可選expand 關鍵字參數,如果設置為 True,就會放大圖像的尺寸,以適應整個旋轉

后的新圖像。

>>>catImg.rotate(90).save('90.png')

>>> catImg.rotate(90,expand=True).save('901.png')

 

 transpose()       翻轉圖像

必須向 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() 更改單個像素

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

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 個參數:xy、text、fill 和 font。

xy 參數是兩個整數的元組,指定文本區域的左上角。

text 參數是想寫入的文本字符串。

可選參數 fill 是文本的顏色。

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

from PIL import ImageFont

ImageFont.truetype()

第一個參數是字符串,表示字體的TrueType 文件,這是硬盤上實際的字體文件。TrueType 字體文件具有.TTF 文件擴展名,通常可以在以下文件夾中找到:

在 Windows 上:C:\Windows\Fonts。

在 OS X 上:/Library/Fonts and /System/Library/Fonts。

在 Linux 上:/usr/share/fonts/truetype。

第二個參數是一個整數,表示字體大小的點數(而不是像素)。請記住,Pillow 創建的PNG 圖像默認是每英寸 72 像素,一點是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  禁止自動防故障功能

pyautogui.PAUSE = 1 每次pyautogui函數調用后暫停一秒

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

 

pyautogui.moveTo(x,y,duration)  將鼠標立即移動到指定位置,duration可選  移動所需秒數

pyautogui.moveRel(x,y,duration)  相對于當前位置移動鼠標x:向右移動多少像素 y:向左移動多少個像素

pyautogui.position()          獲取鼠標位置

 

pyautogui.click(x,y,button=) 點擊鼠標,默認點擊左鍵

在當前位置以外的其他位置點擊,傳入x,y坐標, button 關鍵字參數,值分別為 'left'、'middle'或 'right'

相當于pyautogui. mouseDown()  和pyautogui.mouseUp()的封裝

pyautogui.doubleClick()雙擊鼠標左鍵

pyautogui.rightClick()雙擊鼠標右鍵

pyautogui.middleClick() 雙擊鼠標中建

pyautogui.dragTo()按下左鍵移動鼠標  

pyautogui.dragRel()按下左鍵,相對于當前位置移動鼠標

pyautogui.moveTo()將鼠標移動到指定的x,y坐標

pyautogui.moveRel()相對于當前位置移動鼠標

#!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(#)滾動鼠標,整數向上滾動, 負數向下滾動

 

pyautogui.screenshot()獲取屏幕快照

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

pixelMatchesColor()     如果屏幕上指定的 x、y 坐標處的像素與指定的顏色匹配,返回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()

函數返回4個整數的元組,是屏幕上首次發現該圖像時左邊的x 坐標、頂邊的 y 坐標、寬度以及高度。

找不到圖像,返回None

有多處,返回一個Generator,可以傳遞給list(),返回一個4整數元組列表。

pyautogui.center()返回圖像中心坐標。

>>> 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’,#)  向計算機發送虛擬按鍵,第二個參數暫停時間

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

XYab

pyautogui.KEYBOARD_KEYS 查看鍵盤鍵字符串

python3學習筆記

python3學習筆記

 

pyautogui.press()模擬擊鍵

pyautogui.hotkey()組合按鍵

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

 

【騰訊云】云服務器、云數據庫、COS、CDN、短信等云產品特惠熱賣中

發表評論

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