python3学习笔记

2019年6月5日11:38:50 发表评论 2,543 ℃

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: