Loading

Python程序

烟花

烟花效果

import pygame, math, time, random, os
from sys import exit

WIN_W = 2200
WIN_H = 1300

t1 = 1 #时间流速
show_n = 0
show_frequency = 0.0045    # 0.0045-1烟花绽放频率,数值越大频率越高

color_list = [
    [240, 0, 86],
    [255, 241, 67],
    [255, 137, 54],
    [ 175, 221, 34],
    [68, 206, 246],
    [62, 237, 231],
    [141, 75, 187],
    [249, 144, 111],
    [255, 179, 167],
    [10, 163, 68]
]

pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode((WIN_W, WIN_H),pygame.RESIZABLE, 32)
pygame.display.set_caption("七彩烟花")


sound_wav = pygame.mixer.music.load("2.mp3")
pygame.mixer.music.play()

class Fireworks():
    is_show = False
    x, y = 0, 0#坐标
    vy = 0 #向上的速度
    change_jet_work=False
    start_y = 0
    jet_list=[]#发射粒子
    p_list = []#烟花粒子
    color = [0, 0, 0]
    v = 0#速度

    def __init__(self, x, y, vy, n=300, color=[0, 255, 0], v=10):#这个初始化实际上是没用的
        self.x = x
        self.y = y
        self.vy = vy
        self.color = color
        self.v = v
        for i in range(n):
            self.p_list.append([random.random() * 2 * math.pi, 0, v * math.pow(random.random(), 1 / 3)])
        for i in range(int(n/2)):#喷射粒子的坐标
            self.jet_list.append([random.randint(0,0),0])

    def again(self,x =700,y = 400,color=[0, 255, 0],v=10):#真正的初始化
        self.x = x  # random.randint(100, WIN_W// 2+ 300)
        self.y = y  # random.randint(200, WIN_H//3)#喷射的终点
        if self.x==-1 and self.y==-1:
            return
        self.is_show = True
        self.change_jet_work = False
        self.start_y=900#设置烟花起点
        self.vy = 0
        self.v=v
        self.color = color#color_list[random.randint(0, len(color_list) - 1)].copy()
        n = len(self.p_list)
        self.jet_list = []
        for i in range(int(n)):#喷射粒子的坐标
            self.jet_list.append([random.randint(self.x-1,self.x),self.start_y])
        self.p_list = []
        for i in range(n):
            self.p_list.append([random.random() * 2 * math.pi, 0, self.v * math.pow(random.random(), 1 / 3)])

    def jet(self,speed=110):
        if self.x==-1 and self.y==-1:
            return
        for item in self.jet_list:
            if(item[1]-50>self.y):
                item[1] = item[1] - (random.random() * speed) #调节y上升的速度
            else:
                self.change_jet_work=True#如果有粒子到达爆炸点就切换看烟花
                break

    def run(self):
        if self.x==-1 and self.y==-1:
            return
        global show_n
        for p in self.p_list:
            p[1] = p[1] + (random.random() * 0.6 + 0.7) * p[2]#加就是向下,减就是向上,random用来调速度
            p[2] = p[2] * 0.97
            if p[2] < 1.2:#每次降低颜色,直到是白色就让这个烟花结束
                self.color[0] *= 0.999
                self.color[1] *= 0.999
                self.color[2] *= 0.999

            if max(self.color) < 10 or self.y>WIN_H+p[1]:
                show_n -= 1
                self.is_show = False
                break
        #self.vy += 10 * t1
        #self.y += self.vy * t1

x_set=0
y_set=0
vy_set=20
start = time.time()
run_time=0

fk_list = []
# x, y, vy, n=300, color=[0, 255, 0], 同时发射时v越大,可以先发射
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[0, 224, 158], v=7))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[255, 179, 167], v=8))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[255, 137, 54], v=9))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[255, 137, 54], v=10))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[255, 137, 54], v=10))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[182, 221, 34], v=11))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[182, 221, 34], v=12))
fk_list.append(Fireworks(x_set, y_set, vy_set, n=500, color=[182, 221, 34], v=13))
v_data=[6,7,8,9,10,11,12,14]#烟花大小


seven_jet_data=[[100,350,6],[300,330,7],[500,310,8],[700,290,9],[900,270,11],[1100,250,12],[1300,230,13],[-1,-1,8]]#上升
seven_jet_data_two=[[1300,350,6],[1100,330,7],[900,310,8],[700,290,9],[500,270,11],[300,250,12],[100,230,13],[-1,-1,8]]#上升
seven_jet_data_three=[[170,300,6],[320,260,8],[520,220,11],[720,180,13],[920,220,11],[1120,260,8],[1320,300,6],[-1,-1,8]]#屋盖
seven_jet_data_four=[[100,210,10],[300,210,10],[500,210,10],[700,210,10],[900,210,10],[1100,210,10],[1300,210,10],[-1,-1,8]]#平形
seven_jet_data_five=[[100,180,10],[300,280,10],[500,180,10],[700,280,10],[900,180,10],[1100,280,10],[1300,180,10],[-1,-1,8]]#曲形
seven_jet_data_six=[[320,290,4],[400,520,4],[620,650,4],[810,650,4],[960,520,4],[1080,290,4],[600,190,4],[800,190,4]]#上升
seven_jet_flag=True

clock = pygame.time.Clock()
while True:
    end = time.time()
    run_time=int(end-start)
    if run_time>60:
        show_frequency = 1
    elif run_time>35:
        show_frequency = 0.0075
    elif run_time>25:
        show_frequency = 0.0045
    elif run_time>15:
        show_frequency = 0.0035
    else:
        show_frequency = 0.0025
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.play()
    for event in pygame.event.get():
        #pygame这个不能少,否则退出还在循环
        if event.type == pygame.QUIT:
            exit()
    screen.fill((0, 0, 0))

    if run_time >= 10 and run_time <= 11 or run_time >= 50 and run_time <= 51 \
            or run_time >= 70 and run_time <= 71 or run_time >= 90 and run_time <= 91 \
            or run_time >= 110 and run_time <= 111 or run_time >= 130 and run_time <= 131:
        show_frequency = 0
    if run_time > 11 and run_time < 20 or run_time > 51 and run_time < 60 \
            or run_time > 71 and run_time < 80 or run_time > 91 and run_time < 100 \
            or run_time > 111 and run_time < 120 or run_time > 131 and run_time < 140:
        if seven_jet_flag:
            for i, fk in enumerate(fk_list):
                fk.is_show=False
                seven_jet_flag=False
        for i, fk in enumerate(fk_list):
            if not fk.is_show:
                start_color = color_list[random.randint(0, len(color_list) - 1)].copy()
                #传入again的参数一定要有一个随机。才是因为不能传同样的数据
                if run_time>131:
                    fk.again(seven_jet_data_six[i][0], seven_jet_data_six[i][1], start_color,seven_jet_data_six[i][2])
                elif run_time>111:
                    fk.again(seven_jet_data_three[i][0], seven_jet_data_three[i][1], start_color,seven_jet_data_three[i][2])
                elif run_time>91:
                    fk.again(seven_jet_data_five[i][0], seven_jet_data_five[i][1], start_color,seven_jet_data_five[i][2])
                elif run_time>71:
                    fk.again(seven_jet_data_four[i][0], seven_jet_data_four[i][1], start_color,seven_jet_data_four[i][2])
                elif run_time>51:
                    fk.again(seven_jet_data_two[i][0], seven_jet_data_two[i][1], start_color,seven_jet_data_two[i][2])
                else:
                    fk.again(seven_jet_data[i][0], seven_jet_data[i][1], start_color,seven_jet_data[i][2])
                continue
            if (not fk.change_jet_work):
                fk.jet()
                for item in fk.jet_list:
                    screen.set_at((int(item[0]), int(item[1])), (int(fk.color[0]), int(fk.color[1]), int(fk.color[2])))
            else:
                fk.run()  # 运行一次周围的火花位置就改变一次
                # print(len(fk.p_list))

                for j, p in enumerate(fk.p_list):
                    x, y = fk.x + p[1] * math.cos(p[0]), fk.y + p[1] * math.sin(p[0])
                    if random.random() >= 0.04:
                        screen.set_at((int(x), int(y)), (int(fk.color[0]), int(fk.color[1]), int(fk.color[2])))
                    else:
                        screen.set_at((int(x), int(y)), (255, 255, 255))
    else:
        seven_jet_flag = True
        for i, fk in enumerate(fk_list):
            if not fk.is_show:
                if random.random() < show_frequency * (len(fk_list) - show_n):
                    show_n += 1
                    start_color=color_list[random.randint(0, len(color_list) - 1)].copy()
                    if run_time>30 and run_time<40:
                        fk.again(700,400,start_color,v_data[i])
                    else:
                        position_x=random.randint(150, WIN_W // 2 + 200)
                        position_y=random.randint(200, WIN_H // 3)
                        fk.again(position_x,position_y,start_color,v_data[i])  # 设置烟花初始值
                continue
            if(not fk.change_jet_work):
                fk.jet()
                for item in fk.jet_list:
                    screen.set_at((int(item[0]), int(item[1])), (int(fk.color[0]), int(fk.color[1]), int(fk.color[2])))
            else:
                fk.run()    #运行一次周围的火花位置就改变一次
                for p in fk.p_list:
                    x, y = fk.x + p[1] * math.cos(p[0]), fk.y + p[1] * math.sin(p[0])
                    if random.random() >= 0.04:
                        screen.set_at((int(x), int(y)), (int(fk.color[0]), int(fk.color[1]), int(fk.color[2])))
                    else:
                        screen.set_at((int(x), int(y)), (255, 255, 255))
    pygame.display.update()
    time_passed = clock.tick(150)

对中文或英文进行词频的统计,然后可以创建图云

英文单词统计

#<https://python123.io/resources/pye/hamlet.txt>
#CalHamletV1.py
def getText():
    txt = open("aa.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
 
hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:           
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(100):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

中文词汇统计

#因为分词可能把不是人名的词当作人名也统计,所以程序需要不断优化。根据前面的执行结果来排除一些词
#直到得到正确结果。这是一种编程思想
#<https://python123.io/resources/pye/threekingdoms.txt>
import jieba
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "诸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word == "关公" or word == "云长":
        rword = "关羽"
    elif word == "玄德" or word == "玄德曰":
        rword = "刘备"
    elif word == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
for word in excludes:
    del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

文本转语音

import pyttsx3
words=["大润发今日特价,白菜5元每斤,胡萝卜4元每斤"]
engine = pyttsx3.init()
for i in words:
    engine.say(i)
    engine.runAndWait()

调用Airtable API

#r.request.headers 查看请求信息

import requests
import json
import os
url='<https://api.airtable.com/v0/appU9QT7BUOev35GR/iDM?maxRecords=3&view=Grid%20view>'

def getHtml():
    try:
        kv={'user-agent':'Mozilla/5.0',
            'Authorization':'Bearer key2lrnDfzwxyrgOH'}
        r=requests.get(url,headers=kv)
        r.raise_for_status()
        r.encoding=r.apparent_encoding;
        return r.text
    except:
        print("爬取失败")
        return ""

def pushbots(temperature):

    url='<https://maker.ifttt.com/trigger/test/with/key/c-g2T437UZPrP74Vn7xRuv>'
    data={
        "value1": "这是一条测试\\n当前温度为"+str(temperature)+'C'
    }
    try:
        kv={'user-agent':'Mozilla/5.0'}
        r=requests.get(url,headers=kv,json=data)
        r.raise_for_status()
        r.encoding=r.apparent_encoding;
        print(r.text)
    except:
        print("爬取失败")

text=getHtml()
if(text!=""):
    text=json.loads(text);
    temperature=float(text['records'][0]['fields']['test'][12:])
    pushbots(temperature)
    #print(temperature)

发送Email

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

my_sender = '2580130642@qq.com'  # 发件人邮箱账号
my_pass = 'layfyooxyznediad'  # 发件人邮箱密码
my_user = '1179840055@qq.com'  # 收件人邮箱账号,我这边发送给自己

def mail():
    ret = True
    try:
        for i in range(5):
            msg = MIMEText('这波暖心收下了😁', 'plain', 'utf-8')
            msg['Subject'] = "考研必胜"  # 邮件的主题,也可以说是标题

            server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器,端口是25
            server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
            server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False
        ret = False
    return ret

ret = mail()
if ret:
    print("邮件发送成功")
else:
    print("邮件发送失败")

词云

#GovRptWordCloudv2.py
import jieba
import wordcloud
from scipy.misc import imread
mask = imread("timg2.jpg")
excludes = { }
f = open("aa.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(\
    width = 1000, height = 700,\
    background_color = "white", mask = mask)
w.generate(txt)
w.to_file("grwordcloudm.txt")

python秒杀蓝墨云视频

老师们真的很喜欢在蓝墨云上面放一大堆视频,然后让你去看。反正我是不会去看的。所谓上有政策下有对策~于是~

import requests
import re
def login():
    url1="https://www.mosoteach.cn/web/index.php?c=passport&m=account_login"#登陆的链接
    head1={#这个是数据头
        "Host":"www.mosoteach.cn",
        "Content-Length":"60",
        "Connection": "keep-alive",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Origin": "https://www.mosoteach.cn",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Referer": "https://www.mosoteach.cn/web/index.php?c=passport",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
    username=input("请输入账号:")
    password=input("请输入密码:")
    body="account_name={0}&user_pwd={1}&remember_me=N".format(username,password)#数据包
    result1=requests.post(url1,headers=head1,data=body)#发送请求,并将结果赋给result1

    cookie='''_uab_collina=158250218035462741369747; acw_tc=2f624a3015825021785831656e75d3fe19ff1615824f69523686f655e5c546; teachweb=e0ed1188bf4820414292f2c4fa4b54a6ba26d249; login_token=ed3bece2a19aeb459b92d334882f6ae5d669c4ab0b3a0c3ea5e9c40fce41cc79; SERVERID=c2bbad69fb4f12e536afd9f952c32498|1583987740|1583987499'''


    url2 = "https://www.mosoteach.cn/web/index.php?c=clazzcourse&m=index"
    head2 = {
        "Connection": "keep-alive",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
        "Origin": "https://www.mosoteach.cn",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
        "Referer": "https://www.mosoteach.cn/web/index.php?c=passport",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Cookie": cookie
    }
    result2 = requests.post(url=url2, headers=head2)
    classid = re.findall("data-id=\"(.*)\"", result2.text)
    print("成功获取科目ID:%s" % classid)
    classid = input("请输入你要刷的科目ID:")

    head3 = {
        "Connection": "keep-alive",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
        "Origin": "https://www.mosoteach.cn",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Cookie": cookie,
        "Refere": "https://www.mosoteach.cn/web/index.php?c=interaction&m=index&clazz_course_id={}".format(classid)
    }
    url3 = "https://www.mosoteach.cn/web/index.php?c=res&m=index&clazz_course_id={}".format(classid.replace("'", ""))
    result3 = requests.get(url3, headers=head3)
    viedoid = re.findall("data-value=\"(.*)\"", result3.text)  # 这是用正则表达式提取资源id
    print(viedoid)

    url4 = "https://www.mosoteach.cn/web/index.php?c=res&m=save_watch_to"
    i = list(range(1, len(viedoid), 1))
    # print(i)
    for k in i:
        #if len(viedoid[k]) == len(viedoid[1]):  # 检测所提取的视频id长度是不是等于第一个视频的id长度,因为在提取的过程中后面有几个不是视频id,得把它去掉
            head4 = {
                "Connection": "close",
                "Content-Length": "141",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "Referer": "https://www.mosoteach.cn/web/index.php?c=res&m=index&clazz_course_id={}".format(classid),
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Origin": "https://www.mosoteach.cn",
                "X-Requested-With": "XMLHttpRequest",
                "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
                "Accept-Encoding": "gzip, deflate",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                "Cookie": cookie
            }
            data4 = "clazz_course_id={}&res_id={}&watch_to=1200&duration=1200¤t_watch_to=0".format(classid, viedoid[
                k])  # 这里的watch_to和duration要设置的大一些,如果设置小了,有些视频长度大于这个数值,你就会看不完
            result4 = requests.post(url4, headers=head4, data=data4).json()
            print("视频%s的结果为:%s" % (viedoid[k], result4))

login()
posted @ 2021-05-30 20:00  兔子翻书  阅读(321)  评论(0)    收藏  举报