收集整理了一些有趣的 python 应用(含三方库)
提示电量低
安装库
pip install PyHamcrest
pip install psutil
pip install py-notifier
pip install win10toast
from pynotifier import Notification
import psutil
while 1:
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent
print("是否接通电源:", plugged)
print("当前电池电量:", percent)
if percent < 100 and plugged!=True:
Notification(
title="Battery Low",
description=str(percent) + "% Battery remain!!",
duration=5, # second
).send()
exit(0)
output
是否接通电源: False
当前电池电量: 79
freegames
安装
pip install freegames
查看帮助
python -m freegames --help
output
可以游戏列表,复制游戏源码,查看游戏源码
查看游戏列表
python -m freegames list
查看源码
python -m freegames show ant
output
Exercises
1. Wrap ant around screen boundaries.
2. Make the ant leave a trail.
3. Change the ant color based on position.
Hint: colormode(255); color(0, 100, 200)
"""
from random import *
from turtle import *
from freegames import vector
ant = vector(0, 0)
aim = vector(2, 0)
def wrap(value):
"""Wrap value around -200 and 200."""
return value # TODO
def draw():
"""Move ant and draw screen."""
ant.move(aim)
ant.x = wrap(ant.x)
ant.y = wrap(ant.y)
aim.move(random() - 0.5)
aim.rotate(random() * 10 - 5)
clear()
goto(ant.x, ant.y)
dot(4)
ontimer(draw, 100)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
up()
draw()
done()
运行游戏
python -m freegames.ant
会看见有一只蚂蚁在爬
再试试贪吃蛇
python -m freegames.snake
玩的时候还会显示长度
python -m freegames.pckman
延迟有点高哈
加水印 filestools
安装
pip install filestools
查看属性方法
from watermarker.marker import add_mark
?add_mark
- file: 待添加水印的照片;
- mark: 使用哪些字作为水印;
- out: 添加水印后保存的位置;
- color: 水印字体的颜色,默认颜色#8B8B1B;
- size: 水印字体的大小,默认50;
- opacity: 水印字体的透明度,默认0.15;
- space: 水印字体之间的间隔, 默认75个空格;
- angle: 水印字体的旋转角度,默认30度;接下来,我们仅用一行代码,给图片添加水印。
from watermarker.marker import add_mark
add_mark(file="C://Users/Administrator/Desktop/1.jpg",
out="C://Users/Administrator/Desktop/images/",
mark="么么哒!",
color="red",
opacity=0.2,
angle=45,
space=30)
output
C://Users/Administrator/Desktop/images/1.jpg 保存成功。
添加水印后,最后将处理后的图片保存在一个指定目录下。
输入
输出
5 秒电脑永不熄屏
pip install pyautogui
# 导入相关库
import pyautogui
import random
import time
# 使用while True循环,让程序一直执行!
while True:
x = random.randint(-200,200)
y = random.randint(-200,200)
pyautogui.moveRel(x,y)
time.sleep(5) # 让鼠标移动到某个位置,停留几秒钟,我怕它太累
代码雨
import pygame
import random
def main():
pygame.init()
fullscreen = False
width, height = 1100, 600
init_width, init_height = width, height
# 字块大小,宽高
suface_height = 18
# 字体
font_size = 20
font = pygame.font.Font('C://Windows/Fonts/LCALLIG.ttf', font_size)
# 创建一个窗口
screen = pygame.display.set_mode((init_width, init_height))
# 创建一个图对象
bg_suface = pygame.Surface((init_width, init_height), flags=pygame.SRCALPHA)
pygame.Surface.convert(bg_suface)
bg_suface.fill(pygame.Color(0, 0, 0, 28))
# 用纯色填充
screen.fill((0, 0, 0))
# 显示的字符
letter = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
'z', 'x', 'c', 'v', 'b', 'n', 'm']
texts = [font.render(str(letter[i]), True, (0, 255,0)) for i in range(26)]
# 生成列数
column = int(init_width / suface_height)
drops = [0 for i in range(column)]
while True:
# 按键检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 接受到退出事件后退出
exit()
elif event.type == pygame.KEYDOWN:
# 按 F11 切换全屏或者窗口
if event.key == pygame.K_F11:
print("检测到按键 F11")
fullscreen = not fullscreen
if fullscreen:
# 全屏效果,参数重置
size = init_width, init_height = pygame.display.list_modes()[0]
screen = pygame.display.set_mode(size, pygame.FULLSCREEN | pygame.HWSURFACE)
else:
init_width, init_height = width, height
screen = pygame.display.set_mode((width, height))
# 图像对象重建创建
bg_suface = pygame.Surface((init_width, init_height), flags=pygame.SRCALPHA)
pygame.Surface.convert(bg_suface)
bg_suface.fill(pygame.Color(0, 0, 0, 28))
column = int(init_width / suface_height)
drops = [0 for i in range( column)]
elif event.key == pygame.K_ESCAPE:
# 按 ESC 推出
exit()
# 延时
pygame.time.delay(30)
# 图像对象放到窗口的原坐标上
screen.blit(bg_suface, (0, 0))
for i in range(len(drops)):
# 随机字符
text = random.choice(texts)
# 把字符画到该列的下雨的位置
screen.blit(text, (i * suface_height, drops[i] * suface_height))
# 更新下雨的坐标
drops[i] += 1
# 超过界面高度或者随机数,下雨位置置0
if drops[i] * suface_height > init_height or random.random() > 0.95:
drops[i] = 0
# 更新画面
pygame.display.flip()
if __name__ == "__main__":
main()
F11 全屏,Esc 退出
用 Python 做一个编程语言 20 年的动态排行榜
牛逼操作!我用Python做了一个编程语言20年的动态排行榜!
爬数据,每个日期,画一幅,横轴热度,纵轴语言名称,按热度排序,每帧画柱状图
import requests
import re
import matplotlib.pyplot as plt
r = requests.get("https://www.tiobe.com/tiobe-index/") # 获取网页
r.raise_for_status # 网页状态(200)
total_content = ''.join(re.findall(r'series:(.*?)\}\)', r.text, re.DOTALL)) # 提取网页信息
# 将所有的信息全部提取出来了,包含代码名、时间和影响力
total_content1 = re.findall(r'({.*?})', total_content, re.DOTALL)
lang_dict = {} # 创建空数组,用于存储信息——各种语言在不同日期的热度
for content in total_content1: # 使用循环将信息存入循环数组中
name = ''.join(re.findall(r"{name : '(.*?)'", content, re.DOTALL))
#print(name)
if name == "Visual Basic":
name = 'VB'
elif name == "JavaScript":
name = 'JS'
# 根据特定编程语言构建一个嵌套数组,也可使用lang_dict.setdefault(name,{})
lang_dict[name] = {}
data = re.findall(r'\[Date.UTC(.*?)\]', content, re.DOTALL)
for i in data: # 提取每种语言的年份和影响,存入data的列表中
i = i.replace(' ', '') # 去除空格
i = re.sub(r'[()]', '', i)
value = i.split(',')[-1] # 将影响值取出来,存入value中
data_list = i.split(',')[:3] # 将年份取出来存入data_list
lang_dict[name][str(data_list)]=value # 存入数组
colors = ['k', 'r', 'sienna', 'yellow', 'g',
'aquamarine', 'dodgerblue', 'pink',
'b', 'darkviolet'] # 每种语言作图的颜色
color_dict = {}
# 使用循环对每种语言和颜色进行匹配
for i in range(len(lang_dict.keys())):
color_dict[list(lang_dict.keys())[i]] = colors[i]
# print(lang_dict.keys()) # dict_keys(['Python', 'C', 'C++', 'Java', 'C#', 'JS', 'VB', 'PHP', 'SQL', 'Assembly language'])
# print(lang_dict) # {'Python': {"['2001', '5', '30']": '1.25', "['2001', '6', '30']": '1.13', ...}, ...}
#查看每种语言统计的时间数目
bb = []
cc = []
for i in lang_dict.keys():
a = len(lang_dict[i]) # 每种语言下的时间数目
bb.append((a, i)) # 存储语言和对应的时间数, [(265, 'Python'), (265, 'C'), (265, 'C++'), (265, 'Java'), (265, 'C#'), (265, 'JS'), (160, 'VB'), (265, 'PHP'), (104, 'SQL'), (157, 'Assembly language')]
cc.append(a) # 存储语言数,[265, 265, 265, 265, 265, 265, 160, 265, 104, 157]
# 比较每种语言,把统计最多时间和不足时间的记录下来
dd = []
ee = []
for x, y in bb:
if x < max(cc):
dd.append(y) # 存入不足时间的语言, ['VB', 'SQL', 'Assembly language']
else:
ee.append(y) # 存入最多时间的语言, ['Python', 'C', 'C++', 'Java', 'C#', 'JS', 'PHP']
# 根据时间差异信息把不足的补齐
for i in lang_dict[ee[0]]:
# 取出最多时间的语言的时间
for j in dd:
# 把较少时间的语言的时间取出来,然后根据多的时间补充键值对
lang_dict[j].setdefault(i,0) # 热度补 0
#将所有的信息全部存为以时间为第一层键,值为语言和影响力组成的键值对为值
new_lang_dict = {}
for i in lang_dict.keys():
# 遍历语言
for j in lang_dict[i].keys():
# 遍历时间
m = '-'.join(eval(str(j))) # 将时间先调为字符串,然后使用eval分成各个元素,使用join连接起来
new_lang_dict.setdefault(m, {})
# 根据时间名创建以时间为键,字典为值的键值对
new_lang_dict[m].setdefault(i, lang_dict[i][j])
print(new_lang_dict) # '2001-5-30': {'Python': '1.25', 'C': '20.24', 'C++': '14.20',
# 开始作图
ax = plt.gca()
for index, data_item in enumerate(new_lang_dict.items()):
# 将以时间和时间对应的值取出来,根据时间来做循环来不断显示图片
plt.cla()
a = data_item[1].items() # ("python", "1.25")
b = dict([m, float(n)] for m, n in a) # {"python": 1.25}
# 将每种语言对应的分数更改数据类型,后面用于排序,还是生成字典,放于b中
temp = sorted(b.items(), key=lambda x: x[1]) # 按热度排序
x = [item[0] for item in temp] # 将语言名字存放在x中
color = [color_dict[i] for i in x] # 语言的颜色是固定的
# 每种语言进行的颜色匹配
y = [item[1] for item in temp] # 每种语言对应的分数
plt.barh(range(1, 11), y, color=color) # 做柱状图,水平的
plt.title(data_item[0], fontproperties="simhei", fontsize=24)
plt.yticks(range(1, 11), list(x), fontproperties='simhei', fontsize=16)
plt.xticks(range(0, 30, 100))
for x, y in zip(range(1, 11), y):
plt.text(y+0.1, x-0.1, str(y)) # 将每种语言的分数打印在柱子的后面
plt.pause(0.01)
# plt.savefig(str(index)+".jpg")
plt.show()
合并成了一个 gif
图像叠加
渐变透明度叠加
原图
from PIL import Image
flag = Image.open('1.png').convert("RGBA")
avatar = Image.open('2.jpg').convert("RGBA")
flag = flag.resize(avatar.size)
for i in range(flag.size[0]):
for j in range(flag.size[1]):
r, g, b, _ = flag.getpixel((i, j))
alpha = max(0, 255 - i // 5 - j // 7) # 核心代码,左上角到右下角越来越透明
# 重新填充像素
flag.putpixel((i, j), (r, g, b, alpha))
avatar.paste(flag, (0, 0), flag)
avatar.save('flag_avatar.png')
叠加后的效果