2020年自己敲的一些丢人代码


代码一 明日方舟抽卡模拟器(截至2020年12月17日“孤岛风云”版本)

注:本代码为Python入坑之作,没有当期UP干员概率提升,并且没有任何注释,只有50抽以上六星概率提升与硬保底设定,跑一下当作娱乐就行。

import random
m = input("请输入抽卡次数")
n = int(m)
a = 0
b = 0
c = 0
d = 0
luck = 0
number1 = 0
six = ["棘刺","铃兰","早露","温蒂","傀影","风笛",
       "刻俄柏","阿","煌","莫斯提马","麦哲伦","赫拉格",
       "黑","陈","斯卡蒂","银灰","塞雷娅","星熊","夜莺",
       "闪灵","安洁莉娜","艾雅法拉",
       "伊芙利特","推进之王","能天使","森蚺","史尔特尔","瑕光","泥岩","山"]
five = ["安哲拉","贾维","蜜蜡","断崖","莱恩哈特",
        "月禾","石棉","极境","巫恋","慑砂",
        "惊蛰","吽","灰喉","布洛卡","苇草","槐琥",
        "送葬人","星极","格劳克斯","诗怀雅",
        "夜魔","食铁兽","狮蝎","空","真理","初雪",
        "崖心","守林人","普罗旺斯","可颂","雷蛇","红",
        "临光","华法琳","赫默","梅尔","天火","陨星","白金",
        "蓝毒","幽灵鲨","拉普兰德","芙兰卡","德克萨斯",
        "凛冬","白面鸮","燧石","四月","奥斯塔","絮雨","卡夫卡"]
four = ["孑","卡达","波登可","刻刀","宴","安比尔",
        "梅","红云","桃金娘","苏苏洛","格雷伊","猎蜂",
        "阿消","地灵","深海色","古米","蛇屠箱","角峰","调香师","嘉维尔",
        "末药","暗索","砾","慕斯","霜叶","缠丸","杜宾","红豆",
        "清道夫","讯使","白雪","流星","杰西卡","远山","夜烟","酸糖","芳汀","泡泡","杰克","松果"]
three = ["斑点","泡普卡","月见夜","空爆","梓兰","史都华德",
         "安塞尔","芙蓉","炎熔","安德切尔",
         "克洛斯","米格鲁","卡缇","梅兰莎","翎羽","香草","芬"]
for i1 in range(0,n,1):
    secret = random.randint(1,100)
    if luck <= 50:
        if 1<=secret<=2:
            number1 = random.randint(0,29)
            print(six[number1])
            a = a + 1
        elif secret<=10:
            number2 = random.randint(0,50)
            print(five[number2])
            b = b + 1
        elif secret<=60:
            number3 = random.randint(0,39)
            print(four[number3])
            c = c + 1
        else:
            number4 = random.randint(0,16)
            print(three[number4])
            d = d + 1
    else:        
        if 1 <= secret <= 2 * (luck-49):
            number5 = random.randint(0,26)    
            print(six[number5])
            luck = 0
            a = a + 1
        elif secret <= 2 * (luck-49) +8:
            number6 = random.randint(0,47)
            print(five[number6])
            b = b + 1
        elif secret <= 2 * (luck-49) +58:
            number7 = random.randint(0,36)
            print(four[number7])
            c = c + 1
        else:
            number8 = random.randint(0,16)
            print(three[number8])
            d = d + 1
    luck = luck + 1
print("抽卡结束,共抽到六星" + str(a) + "个,五星" + str(b) + "个,四星" + str(c) + "个,三星" + str(d) + "个,抽出六星比例"+ str(a/n))
p = a / n
if p > 0.02:
    print("双黄出货全满潜")
else:
    print("醒来枕边泪点点")

方舟的所有干员名我已经全部背下来了
代码运行效果:

请输入抽卡次数20
芙蓉
翎羽
白雪
泡普卡
调香师
梅兰莎
史尔特尔
月见夜
空爆
杜宾
贾维
史尔特尔
卡达
蛇屠箱
清道夫
翎羽
泡普卡
猎蜂
卡缇
米格鲁
抽卡结束,共抽到六星2个,五星1个,四星7个,三星10个,抽出六星比例0.1
双黄出货全满潜

代码二 国赛读取EXCEL文件Python代码

代码很短,但短小精悍(100多家企业,可以处理表中的几十万行数据)

import xlrd#引入宏包
data = xlrd.open_workbook(r"F:\数模协会\数模国赛\2020全国大学生数学建模竞赛题\C\附件1:123家有信贷记录企业的相关数据.xlsx")#读取文件
table = data.sheets()[1]#读取表格
print(table.nrows);
p = 1
q = 1#初始寻找位置
for i in range(1,124,1):
    cell_Ei = "E%d"%(i) # E i 号公司统计

    # 找到目标行下一公司 E i + 1 的起始位置 q,当为最后一个公司 E123 时,下一个公司 124 是无法查到的,所以需要特殊处理
    while((table.cell_value(q,0) != "E%d"%(i + 1)) and (q < table.nrows - 1)):
        q = q + 1

    sum = 0 #设置总和的最初值

    if (i == 123) :
        q = q + 1

    # 求和
    for i2 in range(p,q,1):
        a1 = table.cell_value(i2,6)
        sum = sum + float(a1)

    # 移动起始位
    p = q

    # print(cell_A2);

    print(cell_Ei);

    print("%f"%(sum))#打印总和的值

代码三 慕课小项目(一个手绘风图像处理,一个定向图片爬虫,爬虫只能爬确定链接的图片丢死人

手绘风图片处理(我用来处理艾莉的照片)

艾莉原图像

艾莉手绘风处理后图像

这里我使用了图床,搭建图床的目的是让图片直接从国内阿里云仓库而非国外的Github仓库里获取,让图片的加载速度更快。我选择的是阿里云OSS,大公司的服务还有传输速度都非常不错,而且对象存储OSS 的价格一年才8.4元(双12打7折)马爸爸又赚一笔。详情见麻麻,我有自己的图床啦!简单搭建一个廉价、私人、无限制图片大小的稳定图床

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 23:59:07 2020

@author: 李
"""


from PIL import Image
import numpy as np
 
a = np.asarray(Image.open('F:\选修课\python数据分析与展示(慕课)\第一单元:NumPy库 自己调整图片RGB\自己试验\艾莉.jpg').convert('L')).astype('float')

depth = 10 # 这里为虚拟深度,目的是为了实现立体效果,可取值0-100
grad = np.gradient(a) # 取图像灰度的梯度值,以显示各像素点RGB的变化情况
grad_x, grad_y = grad # 将grad在横向和纵向的值赋值给grad_x与grad_y
grad_x = grad_x*depth/100 # 使depth能对图像造成影响
grad_y = grad_y*depth/100
A = np.sqrt(grad_x**2 + grad_y**2 + 1) # 单位化
uni_x = grad_x/A
uni_y = grad_y/A
uni_z = 1/A

vec_el = np.pi/2.2 # 光源的俯视角度,弧度制
vec_az = np.pi/4 # 光源的方向角度,弧度制
dx = np.cos(vec_el)*np.cos(vec_az) # 光源对x轴的影响
dy = np.cos(vec_el)*np.sin(vec_az) # 光源对y轴的影响
dz = np.sin(vec_el)                # 光源对z轴的影响     

b = 255*(dx*uni_x + dy*uni_y + dz*uni_z) # 光源归一化
b = b.clip(0,255) # 为防止数据越界,使RGB值保持在0-255之间

im = Image.fromarray(b.astype('uint8')) # RGB的R、G、B三个值分别由uint8类型数据表示
im.save('F:\选修课\python数据分析与展示(慕课)\第一单元:NumPy库 自己调整图片RGB\自己试验\艾莉手绘.jpg')

定向图片爬虫(需要指定图片地址)

爬取的是明日方舟干员泡泡的精二立绘

import requests
import os

url = "http://prts.wiki/images/4/49/%E7%AB%8B%E7%BB%98_%E6%B3%A1%E6%B3%A1_2.png"
root = "F:\游戏\明日方舟\明日方舟精二图集\\"
path = root + url.split('/')[-1]# url.split('/')[-1]指的是url的最后一部分
try:
    if not os.path.exists(root):# 如果该根目录root不存在,建立一个这样的根目录
        os.mkdir(root)
    if not os.path.exists(path):# 检测文件(path)是否存在,如果文件不存在,从网上下载该文件
        r = requests.get(url)
        with open(path, 'wb') as f:# 打开需要存储的空白图片,将网络上爬取到的图片写入该空白文件中
            f.write(r.content)
            f.close()# 关闭文件
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")

# "r"--以读方式打开,只能读文件,如果文件不存在,会发生异常

# "w"--以写方式打开,只能写文件,如果文件不存在,创建该文件;如果文件已存在,先清空,再打开文件

# "rb"--以二进制读方式打开,只能读文件,如果文件不存在,会发生异常

# "wb"--以二进制写方式打开,只能写文件,如果文件不存在,创建该文件;如果文件已存在,先清空,再打开文件

2020年12月31日更新:

做了一个明日方舟全干员立绘爬虫

代码四 自动读取班级统计表格与打卡情况、年级挂科情况

第一份具有实用性的代码,自此我体会到了,用代码处理文件的高效与快捷

自动读取班级购书统计表格

import xlrd# 引入宏包
data = xlrd.open_workbook(r"C:\Users\李\Desktop\小甲鱼学习python实验文件\数学1901班购买《中文实训写作》情况表.xlsx")#读取文件
table = data.sheets()[0]#读取表格
print(table.nrows)
list = []# 空列表
for i in range(1,30,1):
    cell_Bi = "B%d"%(i)
    cell_Ai = "A%d"%(i)
    if cell_Bi == 1:
        list.append('cell_Ai')
print (list)

自动读取班级打卡情况

from docx import Document
import xlrd
import xlwt
import datetime

#输出今日日期,格式为日/月/年
today_time=datetime.datetime.now().strftime("%Y-%m-%d")
today_Year=datetime.datetime.now().strftime("%Y")
today_month=datetime.datetime.now().strftime("%m")
today_day=datetime.datetime.now().strftime("%d")

#修改读取对象名称为往日日期
today_Year="2020"
today_month="12"
today_day="26"

#读取Word文件里的聊天记录
doc = Document(r"C:\Users\Administrator\Desktop\每日班级打卡统计\自习打卡WORD文件\群内打卡信息-"+today_Year+"年"+today_month+"月"+today_day+"日"+".docx")
print(doc.paragraphs)
for paragraph in doc.paragraphs:
    print(paragraph.text)

#对照班级名单处理Excel表格内的内容
data1 = xlrd.open_workbook(r"C:\Users\Administrator\Desktop\数学1901班学号表.xlsx")#读取文件
table1 = data1.sheets()[0]#读取表格
table2 = xlwt.Workbook(encoding = 'ascii')#创建新的Excel(新的workbook),建议还是用ascii编码
table3 = table2.add_sheet('打卡情况', cell_overwrite_ok=True)#创建新的表单“打卡情况”
for i in range(1,32,1):
    for j in range(0,4,1):
        data2 = table1.cell(i,j).value#对应行列的内容
        print(data2)
        table3.write(i-1,j,label = data2)#复制数学1901班学号表中的内容
for k in range(0,30,1):
    name = table1.cell(k+2,2).value#输出元素(k+2,2)的值
    for paragraph in doc.paragraphs:
        if name in paragraph.text:
            table3.write(k+1,4,label = '已打卡')#写入打卡情况

table2.save(r"C:\Users\Administrator\Desktop\每日班级打卡统计\自习打卡EXCEL文件\群内打卡信息-"+today_Year+"年"+today_month+"月"+today_day+"日"+".xlsx")# 保存文件

自动读取年级挂科情况

# 引入处理文件需要的包
import xlrd
import re # 正则表达式

# 打开文件
data = xlrd.open_workbook(r"C:\Users\李\Desktop\智育成绩读取\19级大一学年智育成绩排名(最终公示版)-程序读取版.xlsx") # 打开文件
table1 = data.sheets()[0] # 打开EXCEL文件的第一个工作表

# 读取EXCEL表的行数列数(选中下述三行按"CTRL+/"即可取消注释(Pycharm中))
# nrows = table1.nrows # 读取行数
# ncols = table1.ncols # 读取列数
# print("行数:%d\n列数:%d"%(nrows,ncols))

# 读取课程名对应的列的数值
# for i in range(0, 32):
#     #print(table1.cell_value(1, i)) # 读取EXCEL中所有的列头
#     if len(table1.cell_value(1, i)) > 3: # 读取课程名对应的列的数值(注意最大的那个i=31为"智育成绩"对应的列的数值)
#         print(table1.cell_value(1, i))
#         print(i)

# 读取挂科的人数
gua1, gua2, gua3, gua4 = 0, 0, 0, 0 # 设置挂科读取初始人数为0
pattern1 = re.compile(r'2019100401\d\d')
pattern2 = re.compile(r'2019100402\d\d')
pattern3 = re.compile(r'2019100403\d\d')
pattern4 = re.compile(r'2019100404\d\d')
for row in range(2, 114): # 初始行令为2
    if int(table1.cell_value(row, 2)) < 60 or int(table1.cell_value(row, 4)) < 60 or int(table1.cell_value(row, 6)) < 60 or int(table1.cell_value(row, 8)) < 60 or int(table1.cell_value(row, 9)) < 60 or int(table1.cell_value(row, 10)) < 60 or int(table1.cell_value(row, 11)) < 60 or int(table1.cell_value(row, 13)) <60 or int(table1.cell_value(row, 15)) < 60 or int(table1.cell_value(row, 17)) < 60 or int(table1.cell_value(row, 19)) < 60 or int(table1.cell_value(row, 21)) < 60 or int(table1.cell_value(row, 23)) < 60 or int(table1.cell_value(row, 25)) < 60 or int(table1.cell_value(row, 27)) < 60 or int(table1.cell_value(row, 29)) < 60:
        # print(table1.cell_value(row, 1)) # 打印全年级挂科学生的学号
        if pattern1.match(table1.cell_value(row, 1)):
            print(table1.cell_value(row, 1)) #打印一班挂科学生的学号
        if pattern1.match(table1.cell_value(row, 1)):
            gua1 = gua1 + 1
        elif re.match(pattern2, table1.cell_value(row, 1)):
            gua2 = gua2 + 1
        elif re.match(pattern3, table1.cell_value(row, 1)):
            gua3 = gua3 + 1
        elif re.match(pattern4, table1.cell_value(row, 1)):
            gua4 = gua4 + 1

# 打印各班挂科的人数
print("一班挂科人数为%d人 二班挂科人数为%d人 三班挂科人数为%d人 四班挂科人数为%d人"%(gua1,gua2,gua3,gua4))

代码五 与Designer.exe的初接触

这篇代码是我们的“Python概论与应用”小组作业,目的是使用给出的x与y的npy文件画出连接后的平滑曲线,我负责了大量的初始工作,这是初始代码(因为初始代码很多是我敲的,而最终版大量优化是noionion做的,所以我在这里只放初始版的代码)

别问我为什么不参与最终版的制作,因为那节课我在重装系统

main.py文件

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from practice1 import Ui_MainWindow#'practice1' is the py file of the ui file

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

import numpy as np
from scipy import interpolate

class MyWindow(QMainWindow):

    def __init__(self):

        super(MyWindow, self).__init__()

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        ## create figure on verticallayout
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.ui.verticalLayout.addWidget(self.canvas)

        ## connection between button and action
        self.ui.xtoolButton.clicked.connect(self.loadx)
        self.ui.ytoolButton.clicked.connect(self.loady)
        self.ui.pushButton.clicked.connect(self.plot)

        ## initial defining
        self.x_raw = np.array([])
        self.y_raw = np.array([])
        self.x_new = np.array([])
        self.y_new = np.array([])

        self.points = np.array([])
        self.method = ''

    def loadx(self):
        selected_file1, _ = QFileDialog.getOpenFileName(self, 'Select Numpy data file ...', '', 'Numpy Files(*.npy)')
        #'_' in the second place means you wonna put nothing there,change (*.npy) to (*.*) means loading can be capable of any type of file
        self.ui.x_rawline.setText(selected_file1)#'x_rawline' is the name of the line following 'x_raw'
        self.x_raw = np.load(selected_file1)

    def loady(self):
        selected_file2, _ = QFileDialog.getOpenFileName(self, 'Select Numpy data file ...', '', 'Numpy Files(*.npy)')
        self.ui.y_rawline.setText(selected_file2)#'y_rawline' is the name of the line following 'y_raw'
        self.y_raw = np.load(selected_file2)

    def interp(self):
    # calculate x new
        num_of_points = int(self.ui.pointnum.text())#'pointnum' is the name of line following 'num of points'
        self.x_new = np.linspace(self.x_raw[0], self.x_raw[-1], num_of_points)

        method = self.ui.comboBox.currentText()#getting the context of the line 'comboBox'
        
        if method == 'Linear':
            interpolator = interpolate.interp1d(self.x_raw, self.y_raw)
        elif method == 'Cubic':
            interpolator = interpolate.interp1d(self.x_raw, self.y_raw, kind='cubic')

        self.y_new = interpolator(self.x_new)

    def plot(self):
        self.interp()

        # clearing old figure
        self.figure.clear()

        # create an axis
        self.ax = self.figure.add_subplot(111)

        # plot data
        self.ax.plot(self.x_new, self.y_new, '*-')

        # refresh canvas
        self.canvas.draw()

app = QApplication([])

win = MyWindow()

win.show()

sys.exit(app.exec())

practice1.py文件(与practice1.ui对接的python文件)

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'F:\选修课\Python概论与应用\期末大作业\程序文件\practice1.ui'
#
# Created by: PyQt5 UI code generator 5.12.3
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(50, 90, 321, 331))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(390, 30, 391, 141))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.y_rawline = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.y_rawline.setObjectName("y_rawline")
        self.gridLayout.addWidget(self.y_rawline, 2, 1, 1, 1)
        self.label = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.x_rawline = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.x_rawline.setObjectName("x_rawline")
        self.gridLayout.addWidget(self.x_rawline, 1, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1)
        self.xtoolButton = QtWidgets.QToolButton(self.gridLayoutWidget)
        self.xtoolButton.setObjectName("xtoolButton")
        self.gridLayout.addWidget(self.xtoolButton, 1, 2, 1, 1)
        self.ytoolButton = QtWidgets.QToolButton(self.gridLayoutWidget)
        self.ytoolButton.setObjectName("ytoolButton")
        self.gridLayout.addWidget(self.ytoolButton, 2, 2, 1, 1)
        self.gridLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget_2.setGeometry(QtCore.QRect(400, 230, 361, 121))
        self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget_2)
        self.label_4.setObjectName("label_4")
        self.gridLayout_2.addWidget(self.label_4, 1, 0, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget_2)
        self.label_3.setObjectName("label_3")
        self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1)
        self.pointnum = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
        self.pointnum.setObjectName("pointnum")
        self.gridLayout_2.addWidget(self.pointnum, 0, 1, 1, 1)
        self.comboBox = QtWidgets.QComboBox(self.gridLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.gridLayout_2.addWidget(self.comboBox, 1, 1, 1, 1)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(530, 420, 131, 61))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "x_raw"))
        self.label_2.setText(_translate("MainWindow", "y_raw"))
        self.xtoolButton.setText(_translate("MainWindow", "..."))
        self.ytoolButton.setText(_translate("MainWindow", "..."))
        self.label_4.setText(_translate("MainWindow", "Mstbod"))
        self.label_3.setText(_translate("MainWindow", "num of points:"))
        self.comboBox.setItemText(0, _translate("MainWindow", "Linear"))
        self.comboBox.setItemText(1, _translate("MainWindow", "Cubic"))
        self.pushButton.setText(_translate("MainWindow", "Plot"))

代码效果如下:

视频上传到图床有点占用空间,所以调用的B站视频(将B站当作视频床,这里用的是最终版的效果)

通过这次大作业的编写,我深刻认识到了团队合作抱紧大佬大腿的重要性,原来,一个高效合作的团队强大的大佬才是项目的关键\暗中观察

暂时就这么多啦,让我们明年再战!


文章作者: Heart-of-engine
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Heart-of-engine !
打赏
  目录