PythonModule

easygui

  • easygui是Python的一个图形化界面的库。

  • 下载模块

    pip install easygui

常用功能

  1. 消息弹窗

    msgbox()   #消息弹窗
    msgbox(msg=' ', title=' ', ok_button=' ', image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    ok_button:#按钮上显示的信息
    image:#显示图片(需要路径)
    #返回值:
    #按钮信息
    #右上角×号返回None
    #########################
    import easygui as t
    t.msgbox('Hello','easy','Yes','wjx.png')
  2. 双项选择

    ccbox() #双项选择
    ccbox(msg=' ', title=' ', choices=(' ', ' '), image=None)
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式,两个选项显示的内容
    image:#显示图片(需要路径)
    #返回值:
    #第一个按钮返回True
    #第二个按钮返回False
    #右上角×号返回None
    import easygui as t
    t.ccbox('下面水果,你喜欢哪一个?','选择',('苹果','橘子'))
  3. 多项选择

    buttonbox()   #多项选择
    buttonbox(msg=' ', title=' ', choices=('Button1', 'Button2', 'Button3'), image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式或列表的形式,多个选项显示的内容
    image:#显示图片(需要路径)
    #返回值:
    #点击按钮返回按钮的信息
    #右上角×号返回None
    import easygui as t
    tuple = ('石头','剪刀','布')
    t.buttonbox('选择石头剪刀布','game',tuple)
  4. 可选的下拉列表

    choicebox()与multchoicebox()——#可选的下拉列表
    choicebox(msg=' ', title=' ', choices=())
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式或列表的形式,多个选项显示的内容
    #返回值:
    #点击显示的选项,返回选项的信息
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    import easygui as t
    list = ['石头','剪刀','布']
    t.choicebox('选择石头剪刀布','game',list)
    multchoicebox()#功能同样,只是他可以提供多选,拥有全选与全清按钮。
    #返回值:
    # 多选的返回值是多选的文本列表
    # 点击Cancel按钮返回None
    # 右上角×号返回None
  5. 文本输入框

    enterbox()    #文本输入框
    enterbox(msg=' ', title=' ', default=' ', strip=True, image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    strip:#的值为True时会自动忽略输入的首尾空格,False则相反
    image:#显示图片(需要路径)
    #返回值:
    ## 输入内容后返回值为输入的字符串
    #点击Cancel按钮返回None
    #右上角×号返回None
     
    import easygui as t
    s = t.enterbox('What do you want to say ?','想说什么','Who are you ?')
    print(s)
  6. 数字输入

    integerbox() # 数字输入
    integerbox(msg='', title=' ', default='', lowerbound=0, upperbound=99, image=None, root=None,)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    lowerbound:#输入的最小值
    upperbound:#输入的最大值
    image:#显示图片(需要路径)
    #返回值:
    # 输入内容后返回值为输入的数字
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    #输入数值超出范围时会给出提示后从新输入。
    import easygui as t
    s = t.integerbox('你多大了','年龄','18',0,120)
    print(s)
  7. 多选项输入

    mulenterbox()  #多选项输入
    multenterbox(msg=' ', title=' ', fields=(), values=())
    msg:#需要显示的内容
    title:#窗口的标题
    fields:#填写条目名称
    values#默认内容
    #返回值:
    ### 输入内容后返回值为输入的内容,以列表的形式
    # 点击Cancel按钮返回None
    ## 右上角×号返回None
    import easygui as t
    message = ['学号', '姓名','性别','年龄','院系','入学时间']
    s = student = t.multenterbox('输入学生的信息:', '信息录入', message)
    print(s)
  8. 密码输入框

    passwordbox()#密码输入框(不显示)
    passwordbox(msg=' ', title=' ', default=' ', image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    image:#显示图片(需要路径)
    #返回值:
    # 输入内容后返回值为输入的字符串
    ## 点击Cancel按钮返回None
    # 右上角×号返回None
    import easygui as t
    s = t.passwordbox('输入密码', '密码')
    print(s)
  9. 多项显示

    multpasswordbox() #多项显示
    multpasswordbok(msg=' ', title=' ',fields=(),values=())
    msg:#需要显示的内容
    title:#窗口的标题
    fields:#填写条目名称,最后一栏显示为*号
    values#默认内容
    #返回值:
    # 输入内容后返回值为输入的内容,以列表的形式
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    import easygui as t
    s = t.multpasswordbox('请输入账号密码', '登录',['用户名','账号','密码'],['123','123','123'])
    print(s)

openpyxl

  • 安装模块

    pip install openpyxl

常用功能

1.sheet

from openpyxl import load_workbook
#打开excel文件
workbook = load_workbook("文件名")
#1.获取所有的sheet名称
name_list = workbook.sheetnames
print(name_list)
#2.根据名称获取sheet
sheet_object = workbook["sheetname"]
print(sheet_object)
#3.根据索引获取sheet
sheet = worksheets[0]
#4.循环获取所有的sheet
for sheet_object in wcrkbook:
   print(sheet_object)
#不加.sheetnames内部也是自动获取sheetnames的

2.sheet中单元格的数据

from openpyxl import load_workbook
workbook = load_workbook("文件路径")
sheet = workbook.worksheets[1]
#1.获取 第n行 &第n列 的单元格(起始位置是1)
cell = sheet.cell(1,1)
print(cell)
print("内容",cell.value)
print("样式",cell.style)
print("字体",cell.font)
print("排序",cell.alignment)
#2.根据Excel的位置获取数据
cell_al = sheet["A1"]
print(cell_al.value)
#3.获取第n行的单元格
cell_list = sheet[1]
for cell in sheet[1]:
   print(cell.value)
   
#4.循环获取所有行数据
for row in sheet.rows:
   print(row[0].value)
   
#5.循环获取所有列
for col in sheet.columns:
   print(col[0].value)

3.合并的单元格

from openpyxl import load_workbook
workbook = load_workbook("文件路径")
sheet = workbooks[2]
#1.获取单元格
c1 = sheet.cell(1,1)
print(c1) #<cell "Sheet1".A1>
print(c1.value) #用户信息
#第一个和第二个合并单元格,第一个显示值,第二个显示null
c1 = sheet.cell(1,2)
print(c1) #<MergedCell "Sheet1".B1>
print(c1.value) #None

4.Excel

4.1原Excel文件基础上写内容

from openpyxl import load_workbook
workbook = load_workbook("文件路径")
sheet = worksheets[0]
#1.找到单元格,并修改单元格的内容
cell = sheet.cell(1,1)
cell.value = "值"
#将excel文件保存到p2.xlsx文件中
workbook.save("文件路径")

4.2新创建Excel文件写内容

from openpyxl import workbook
#创建excel且默认会创建一个sheet(名称为sheet)
workbook = workbook.Workbook()
sheet = worksheets[0]
#找到单元格,并修改单元格的内容
cell = sheet.cell(1,1)
cell.value = "值"
#将excel文件保存到p2.xlsx文件中
workbook.save("文件路径")

4.3删除和修改

from openpyxl import workbook
workbook = workbook.workbook()
#1.修改sheet名称
sheet = worksheets[0]
sheet.title = "值"
workbook.save("p2.xlsx")
#2.创建sheet并设置sheet颜色
sheet = workbook.create_sheet("工作计划",0)#零代表位置
sheet.sheet_properties.tabColor = "1072BA"
workbook.save("P2.xlsx")
#3.默认打开的sheet
workbook.active = 0
workbook.save("p2.xlsx")
#4.拷贝sheet
sheet = workbook.create_sheet("工作计划")
sheet.sheet_properties.tabColor = "1072BA"
new_sheet = workbook.copy_worksheet(workbook["Sheet"])
new_sheet.title = "新的计划"
workbook.save("p2.xlsx")
#5.删除sheet
del workbook["用户列表"]
workbook.save("files/p2.xlsx")

5.操作单元格

from openpyxl import load_workbook
from openpyxl.styles import Alignment,Border,Side,Font,PatternFill,GradientFill
workbook = load_workbook("文件")
sheet = workbook.worksheet[1]
#1.获取某个单元格,修改值
cell = sheet.cell(1,1)
cell.value = "开始"
#2.获取某个单元格,修改值
sheet["V3"] = "Alex"
vb.save("p2.xlsx")
#3.获取某些单元格,修改值
cell_list = sheet[B2:C3]
#b2到c3拿到的值是(b2,b3,c2,c3)
for row in cell_list:
   for cell in row :
       cell.value = "新的值"
vb.save("p2.xlsx")
#4.对齐方式
cell = sheet.cell(1,1)
#herizontal,水平方向对齐方式:“general”,"left","center"句中,"right","fill","justify","centercontinuous","distributed"
#vertieal,垂直方向对齐方式:"top","center","bottom","justify","distributed"
#text_rotation,旋转角度
#wrap_text,是否自动换行
cell.alignment = Alignment(horizontal="center",vertical="distributed",text_rotation=45,wrap_text=True)
wb.save("p2.xlsx")
#5.边框
#side的style有如下:dashDot,dashDotDot,dashed,dotted,double,hair,mediun,mediumDashDot,mediumDashDotdot,mediumDashed,slantDashDot,thick,thin.
sell = sheet.cell(9.2)
cell.border = Border(
top = Side(style="thin",color="FFB6C1"),  
   bottom=Side(style="dashed",color="9932cc"),
   left=Side(style="dashed",color="9932cc"),
   right=Side(style="dashed",color="9932cc"),
   diagonal=Side(style="thin",color="483D8B"),#对角线
   diagonalUp=True,#左下-右上
   #diagonalDown=True #左上-右下
)
wb.save("p2.xlsx")
#6.字体
cell = sheet.cell(5,1)
cell.font = Font(name="微软雅黑",size=45,color="ff0000",underline="single") #underline下划线
wb.save("p2.xlsx")
#7.背景色
cell = sheet.cell(5,3)
cell.fill = PatternFill("solid",fgColor="99ccff")
wb.save("p2.xlsx")
#8.渐变背景色
cell = sheet.cell(5,5)
cell.fill = GradientFill("linear",stop=("FFFFFF","99ccff","000000"))#从左到右的三个颜色
wb.save("p2.xlsx")
#9.宽高(索引从1开始)
sheet.row_idmensions[1].height = 50
sheet.column_dimensions["E"].width = 100
wb.save("p2.xlsx")
#10.合并单元格
sheet.merge_cells("B2:D8")
#这是两种
sheet.merge_cells(start_row=15,start_column=3,end_row=18,end_column=8)
wb.save("p2.xlsx")
#这是解除合并单元格的
sheet.unmerge_cells("B2:D8")
wb.save("p2.xlsx")
#11.写入公式
sheet = wb.worksheets[3]
sheet["D1"] = "合计"
sheet["D2"] = "=B2*C2"
wb.save("p2.xlsx")
sheet = wb.worksheets[3]
sheet["D3"] = "=sum(B3,C3)"
wb.save("p2.xlsx")
#12.删除
#idx,要删除的索引位置
#anount,从索引位置开始要删除的个数(默认为1)
sheet.delete_rows(idx=1,anount=2)
sheet.delete_cols(idx=1,anount=3)
wb.save("p2.xlsx")
#13.插入
sheet.insert_rows(idx=5,anount=10)
sheet.insert_cols(idx=3,anount=2)
wb.save("p2.xlsx")
#14.循环写内容
sheet = wb["Sheet"]
cell_range = sheet["A1:C2"]
for row in cell_range:
   for cell in row:
       cell.value = "xx"
#第5行第1列到第7行第10列
for row in sheet.iter_rows(min_row=5,min_col=1,max_col=7,max_row=10):
   for cell in row:
       cell.value = "oo"
wb.save("p2.xlsx")
#15.移动
#将H2:J10范围的数据,向右移动15个位置、向上移动1个位置
sheet.nove_range("H2:J10",rows=-1,cols=15)
wb.save("p2.xlsx")
#16.打印区域
sheet.print_area = "A1:D200"
wb.save("p2.xlsx")
#17.打印时,每个页面的固定表头
sheet.print_title_cols = "A:D"
sheet.print_title_rows = "1:3"
wb.save("p2.xlsx")

6.作业

  1. 补充代码:实现去网上获取指定地区的天气信息,并写入excel中。

    import requests
    while True:
       city = input("请输入城市(Q/q退出):")
       if city.upper()=="Q":
           break
       url = "http://ws.webxml.com.cn//webServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName={}".format(city)
       res = requests.get(url=url)
       print(res.text)
       
       #1.提取xml格式中的数据
       #2.为每个城市创建一个sheet,并将获取的xml格式中的数据写入到excel中。
       from openpyxl import load_workbook
           workbook = load_workbook("a1.xlsx")
           sheet = workbook.create_sheet("工作计划")
           sheet.title = city
           sheet = workbook[city]
           cell=sheet["A1:AH1"]
           text=str(res.text)[:-16].split("<string>")[1:]
           for i in range(len(text)):
               cell[0][i].value = text[i][:-13]
               print(text[i][:-13])
           workbook.save("a1.xlsx")
  2. 读取ini文件内容,按照规则写入到Excel中

    [mysqld]
    datadir=/var/lib/mysql
    socket=py-mysql-bin
    log-bin=py-mysql-bin
    character-set-server=utf8
    collation-server=utf8_general-ci
    log-error=/var/log/mysqld.log
    symbolic-links=0
    [mysqld_safe]
    log-error=/var/log/mariadb/mariadb/mariadb.log
    pid-file=/var/run/mariadb/mariadb.pid
    [client]
    default-character-set=utf8
    #1.读取ini格式的文件,并创建一个excel文件,并且每个节点创建一个sheet,然后将节点下的键值写入到excel中。
    #2.首行,字体白色&单元格背景色蓝色
    #3.内容均句中
    #4.边框

Matplotlib and Plotly

  • 安装 Matplotlib and Plotly

    pip install matplotlib
    pip install Plotly

1.Matplotlib

  1. 基本使用

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    x_values = range(1, 1001, 19)
    y_values = [x**2 for x in x_values] # 自动计算数据
    # 写上这两行后可以解决,字体无法显示的问题。
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    # print(plt.style.available) # 查看样式
    plt.style.use("Solarize_Light2") # 网格样式
    fig, ax = plt.subplots()
    # 隐藏xy轴,写这个可以隐藏坐标轴
    # ax.get_xaxis().set_visible(False)
    # ax.get_yaxis().set_visible(False)
    ax.scatter(x_values, y_values, c="red", s=1) # 调用scatter()并使用参数s设置绘制图形时使用的点的尺寸,c是颜色。
    # ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=100)
    # c是颜色,写数据是透明色的透明度,cmap=plt.cm.Blues是告诉pyplot使用什么渐变颜色
    ax.set_title("平方数", fontsize=24)                      # 表标题,字号24
    ax.set_xlabel("值", fontsize=14) # x轴标题,字号14
    ax.set_ylabel("值的平方", fontsize=14) # y轴标题,字号14
    ax.tick_params(axis="both", which="major", labelsize=14)  # 设置刻度标记的大小。
    ax.axis([0, 1100, 0, 1100000]) # 设置每个坐标轴的取值范围
    # plt.savefig("squares_plot.png", bbox_inches="tight") # 这个方法是用来保存图片的,第一个参数是图片的名称,第二个是去掉多余的白边,
    plt.show()
  2. 将数据以逗号翻个的称为CSV文件,对人阅读比较麻烦,但是程序可以轻松提取并处理。

    import csv
    from datetime import datetime
    import matplotlib.pyplot as plt
    with open("aa.csv") as f:
       reader = csv.reader(f) #将存储的对象最为实参
       header_row = next(reader) #传入阅读器对象时,它将返回文件中的下一行
      # for index,column_header in enumerate(header_row): # enumerate用于获取索引及其值
       #     print(index,column_header)
       dates, highs, lows = [], [], []
       for row in reader: #循环获取
           current_date = datetime.strptime(row[2], "%Y-%m-%d") #索引获取时间并转为时间类型
           # 时间参数还有很多
           # %A   星期几,%B   英文月份名,%m   数字月份名,%d   数字天数,
           # %Y   四位年份,%y   两位年份,%H   24小时制小时数,%I   12小时制小时数,
           # %p   am或pm,%M   分钟数,%S   秒数
           try:
               high = int(row[5]) #获取索引5处的数据
               low = int(row[6])
           except ValueError: #在天气的之中会出现没有值的情况,刚好ValueError可以检测到这个错误。
          print(f"Missing data for {current_date}")
           else:
               dates.append(current_date)
               highs.append(high)
               lows.append(low)
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.style.use("seaborn")
    fig,ax = plt.subplots()
    ax.plot(dates, highs, C="red", alpha=0.5) # alpha透明度,0透明,1不透明。
    ax.plot(dates, lows, C="blue", alpha=0.5)
    ax.fill_between(dates,highs,lows,facecolor="blue",alpha=0.1) #x,y,y,facecolo颜色, alpha透明度,0透明,1不透明。
    ax.set_title("2018年7月每日最高气温", fontsize=24)
    ax.set_xlabel("", fontsize=14)
    fig.autofmt_xdate() # 绘制倾斜的标签
    ax.set_ylabel("温度", fontsize=14)
    plt.show()

2.Plotly

  1. 基本使用

    from random import randint
    class Die:
       def __init__(self, num_sides=6):
           self.num_sides = num_sides
       def roll(self):
           return randint(1, self.num_sides) # randiint用于生成随机数
           
    die1 = Die()
    die2 = Die()
    results = [die1.roll()+die2.roll() for roll_num in range(100)]
    frequencies = [results.count(value) for value in range(1, (die1.num_sides+die2.num_sides)+1)]
    print(results)
    print(frequencies)
    # 绘制直方图
    from plotly.graph_objs import Bar,Layout
    from plotly import offline
    x_values = list(range(2, (die1.num_sides+die2.num_sides)+1))
    data = [Bar(x=x_values, y=frequencies)] # 收集数据
    x_axis_config = {"title":"结果","dtick":1}   # x标题及属性设置,dtick是刻度间距
    y_axis_config = {"title":"结果的频率"} # y标题及属性设置
    my_layout = Layout(title="2骰子1000次的结果", xaxis=x_axis_config, yaxis=y_axis_config) # 标题整理
    offline.plot({"data":data,"layout":my_layout}, filename="d6.html") # 渲染并保存
  2. json是使用非常广泛的数据格式。

    import json
    import plotly.express as px
    """
    print(px.colors.named_colorscales()) #这个方法可以查看,可以使用的渐变。
    """
    with open("bbb.json") as f:
       all_eq_data = json.load(f) # load用于将json转为可以处理的格式
    """
    with open("ccc.json","w") as f:
      json.dump(all_eq_data,f,indent=4) # dump接收一个json数据和一个文件数据,indent用于结构匹配的缩进。
    """  
    all_eq_dicts = all_eq_data["features"]
    mags, titles, lons, lats = list(), list(), list(), list()
    for eq_dict in all_eq_dicts:
       mag = eq_dict["properties"]["mag"]
       title = eq_dict["properties"]["title"]
       lon = eq_dict["geometry"]["coordinates"][0]
       lat = eq_dict["geometry"]["coordinates"][1]
       mags.append(mag)
       titles.append(title)
       lons.append(lon)
       lats.append(lat)
       
    fig = px.scatter(
    x=lons,
       y=lats,
       labels={"x":"经度","y":"纬度"},
      range_x=[-200,200] #范围
      range_y=[-90,90]
       width=800, #宽高800像素
       height=800,
       title="全球地震散点图",
       size = mags, #默认点尺寸为20像素
       size_max=10, #最大显示尺寸缩放到10
    color = mags, #设置渐变
       hover_name = titles #震级大致位置
    )
    fig.write_html("global_earthquakes.html") # 保存
    fig.show() #查看

     

sys

  • sys模块提供了一系列有关Python运行环境的变量和函数。

  • sys.argv,可以获取当前正在执行的命令行参数的参数列表(list)。 变量解释

    sys.argv[0]当前程序名

    sys.argv[1]第一个参数

    sys.argv[2]第二个参数

    len(sys.argv)-1 参数个数(减去文件名)

    import sys
    print(sys.argv)
    print(sys.argv[0])
    print(sys.argv[1])
    print("第二个参数:%s"%sys.argv[2])
    print("参数个数:%s"%(len(sys.argv)-1))
    -------------------结果:
    #python /root/mcw.py arg1 arg2
    ['/root/mcw.py', 'arg1', 'arg2']
    /root/mcw.py    #当前程序名
    arg1
    第二个参数:arg2
    参数个数:2
    2) 如果执行用的相对路径,返回的是相对路径
    print(sys.argv[0])
    ----------------结果:
    [root@xiaoma /root] test!
    #python ./mcw.py
    ./mcw.py#sys.argv =['/root/mcw.py', 'arg1', 'arg2'] ,列表第一个元素为程序执行相对路径,第二个元素开始为程序传参
  • sys.path

    返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

    import sys
    print(sys.path)
    ---------------------结果:
    ['D:\\aPython_full目录\\小马过河的代码练习', 'C:\\mcw', 'C:\\mcw\\venv\\Scripts\\python36.zip', 'C:\\python3\\DLLs', 'C:\\python3\\lib', 'C:\\python3', 'C:\\mcw\\venv', 'C:\\mcw\\venv\\lib\\site-packages', 'C:\\mcw\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg', 'C:\\mcw\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg', 'C:\\软件安装\\PyCharm 2018.3.5\\helpers\\pycharm_matplotlib_backend']
    添加系统环境变量:
    import sys,os
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    print(BASE_DIR)
    #添加系统环境变量
    sys.path.append(BASE_DIR)
    print(sys.path)
    import sys
    sys.path.append("C:\python3\Scripts")
    print(sys.path)
    ------------------结果:
    ['D:\\.........., 'C:\\python3\\Scripts']
  • sys.platform

    获取当前执行环境的平台,如win32表示是Windows系统,linux2表示是linux平台

    print(sys.platform)
    -------------结果:
    win32  
    -------------结果:
    [root@xiaoma /root] test!
    #python mcw.py
    linux2
  • sys.exit(n)

    调用sys.exit(n)可以中途退出程序,当参数非0时,会引发一个SystemExit异常,从而可以在主程序中捕获该异常。

    #vim mcw.py
    import sys
    sys.exit(3)
    ----------结果:
    [root@xiaoma /root] test!
    #python mcw.py
    [root@xiaoma /root] test!
    #echo $?
    3
  • sys.version

    获取Python解释程序的版本信息

    import sys
    print(sys.version)
    --------------结果:
    3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)]
    import sys
    print(sys.version)
    --------------结果:
    [root@xiaoma /root] test!
    #python mcw.py
    2.7.5 (default, Nov  6 2016, 00:28:07)
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
  • sys.getrefcount

    获取一个值的应用计数

    a = [11,22,33]
    b = a
    print(sys.getrefcount(a))
    --------------结果:
    3 #a,b,还有gerefcount方法三个都在使用这个列表
  • sys.getrecursionlimit python默认支持的递归数量

  • sys.stdout.write     可以做输出重定向

    for i in range(3):
       print("魔降风云变")
    import sys
    for i in range(3):
       sys.stdout.write('小马过河')
    -----------------结果:
    魔降风云变
    魔降风云变
    魔降风云变
    小马过河小马过河小马过河
    import sys
    for i in range(3):
       sys.stderr.write('小马过河')
    ------------------结果:
    小马过河小马过河小马过河

    stdout 是一个类文件对象;调用它的 write 函数可以打印出你给定的任何字符串。 实际上,这就是 print 函数真正做的事情;它在你打印的字符串后面加上一个硬回车,然后调用 sys.stdout.write 函数。 在最简单的例子中,stdout 和 stderr 把它们的输出发送到相同的地方 和 stdout 一样,stderr 并不为你添加硬回车;如果需要,要自己加上。 stdout 和 stderr 都是类文件对象,但是它们都是只写的。 它们都没有 read 方法,只有 write 方法。然而,它们仍然是类文件对象,因此你可以将其它任何 (类) 文件对象赋值给它们来重定向其输出。

  • sys.modules

    import sys,os
    print(sys.modules.keys())
    -----------------------结果;
    dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'nt', 'winreg', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', '_bootlocale', '_locale', 'encodings.gbk', '_codecs_cn', '_multibytecodec', 'sysconfig', 'encodings.cp437', 'sitecustomize'])

xlrd

1.背景

  • 安装模板:

    #到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。
    #在cmd命令行输入:pip install xlrd
  • xlrd介绍:xlrd是python环境下对excel中的数据进行读取的一个模板,可以进行的操作有: 读取有效单元格的行数、列数

    读取指定行(列)的所有单元格的值

    读取指定单元格的值

    读取指定单元格的数据类型

2.常用函数

  1. 打开文件(获取一个工作表):

    import xlrd
    data = xlrd.open_workbook("01.xls") # 打开当前目录下名为01.xls的文档
    #此时data相当于指向该文件的指针
    table = data.sheet_by_index(0) # 通过索引获取,例如打开第一个sheet表格
    table = data.sheet_by_name("sheet1") # 通过名称获取,如读取sheet1表单
    table = data.sheets()[0] # 通过索引顺序获取
    # 以上三个函数都会返回一个xlrd.sheet.Sheet()对象
    names = data.sheet_names()   # 返回book中所有工作表的名字
    data.sheet_loaded(sheet_name or indx)   # 检查某个sheet是否导入完毕
  2. 对行进行操作:

    nrows = table.nrows # 获取该sheet中的有效行数
    table.row(rowx) # 返回由该行中所有的单元格对象组成的列表
    table.row_slice(rowx) # 返回由该列中所有的单元格对象组成的列表
    table.row_types(rowx, start_colx=0, end_colx=None)  # 返回由该行中所有单元格的数据类型组成的列表
    table.row_values(rowx, start_colx=0, end_colx=None) # 返回由该行中所有单元格的数据组成的列表
    table.row_len(rowx) # 返回该列的有效单元格长度
  3. 对列进行操作:

    ncols = table.ncols # 获取列表的有效列数
    table.col(colx, start_rowx=0, end_rowx=None) # 返回由该列中所有的单元格对象组成的列表
    table.col_slice(colx, start_rowx=0, end_rowx=None) # 返回由该列中所有的单元格对象组成的列表
    table.col_types(colx, start_rowx=0, end_rowx=None) # 返回由该列中所有单元格的数据类型组成的列表
    table.col_values(colx, start_rowx=0, end_rowx=None) # 返回由该列中所有单元格的数据组成的列表
  4. 对单元格进行操作:

    table.cell(rowx, colx) # 返回单元格对象
    table.cell_type(rowx, colx) # 返回单元格中的数据类型
    table.cell_value(rowx,colx) # 返回单元格中的数据

pygame

  1. 安装Pygame

    pip install pygame
  2. Pygame常用模块

    模块名 功能
    pygame.cdrom 访问光驱
    pygame.cursors 加载光标
    pygame.display 访问显示设备
    pygame.draw 绘制形状、线和点
    pygame.event 管理事件
    pygame.font 使用字体
    pygame.image 加载和存储图片
    pygame.joystick 使用游戏手柄或者类似的东西
    pygame.key 读取键盘按键
    pygame.mixer 声音
    pygame.mouse 鼠标
    pygame.movie 播放视频
    pygame.music 播放音频
    pygame.overlay 访问高级视频叠加
    pygame.rect 管理矩形区域
    pygame.scrap 本地剪贴板访问
    pygame.sndarray 操作声音数据
    pygame.sprite 操作移动图像
    pygame.surface 管理图像和屏幕
    pygame.surfarray 管理点阵图像数据
    pygame.time 管理时间和帧信息
    pygame.transform 缩放和移动图像
  • 简单示例:

    import pygame
    import sys
    pygame.init()  # 初始化pygame
    size = width, height = 320, 240  # 设置窗口大小
    screen = pygame.display.set_mode(size)  # 显示窗口
    while True:  # 死循环确保窗口一直显示
       for event in pygame.event.get():  # 遍历所有事件
           if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
               sys.exit()
    pygame.quit()  # 退出pygame
  1. 制作一个跳跃的小球游戏

    • 创建一个游戏窗口,然后在窗口内创建一个小球。以一定的速度移动小球,当小球碰到游戏窗口的边缘时,小球弹回,继续运动按照如下步骤实现该功能:创建游戏窗口

    • 创建一个游戏窗口,宽和高设置为640*480。代码如下:

      import sys
      import pygame
      pygame.init()                       # 初始化pygame
      size = width, height = 640, 480     # 设置窗口大小
      screen = pygame.display.set_mode()  # 显示窗口
      import sys
      import pygame
      pygame.init()                       # 初始化pygame
      size = width, height = 640, 480     # 设置窗口大小
      screen = pygame.display.set_mode()  # 显示窗口
    • 上述代码中,首先导入pygame模块,然后调用init()方法初始化pygame模块,接下来,设置窗口的宽和高,最后使用display模块显示窗体。

  2. display模块的常用方法

    方法名 功能
    pygame.display.init() 初始化display模块
    pygame.display.quit() 结束display模块
    pygame.display.get_init() 如果display模块已经被初始化,则返回True
    pygame.display.set_mode() 初始化一个准备显示的界面
    pygame.display.get_surface() 获取当前的Surface对象
    pygame.display.flip() 更新整个待显示的Surface对象到屏幕上
    pygame.display.update() 更新部分内容显示到屏幕上,如果没有参数,则与flip功能相同(上一条)
  • 保持窗口显示

    • 运行第一步的代码后会出现一个一闪而过的黑色窗口,这是因为程序执行完成后,会自动关闭。如果想要让窗口一直显示,需要使用while True让程序一直执行,此外,还需要设置关闭按钮。具体代码如下:

      import pygame
      import sys
      pygame.init()  # 初始化pygame
      size = width, height = 320, 240  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      while True:  # 死循环确保窗口一直显示
         for event in pygame.event.get():  # 遍历所有事件
             if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                 sys.exit()
      pygame.quit()  # 退出pygame

      上述代码中添加了轮询事件检测。pygame.event.get()能够获取事件队列,使用for...in遍历事件,然后根据type属性判断事件类型。这里的事件处理方式与GUI类似,如event.type等于pygame.QUIT表示检测到关闭pygame窗口事件,pygame.KEYDOWN表示键盘按下事件,pygame.MOUSEBUTTONDOWN表示鼠标按下事件等。

  • 加载游戏图片

    • 在窗口添加小球。我们先准备好一张ball.png 图片,然后加载该图片,最后将图片显示在窗口中,具体代码如下:

      import pygame
      import sys
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      while True:  # 死循环确保窗口一直显示
         for event in pygame.event.get():  # 遍历所有事件
             if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                 sys.exit()
         screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
         screen.blit(ball, ballrect)  # 将图片画到窗口上
         pygame.display.flip()  # 更新全部显示
      pygame.quit()  # 退出pygame

      上述代码中使用iamge模块的load()方法加载图片,返回值ball是一个Surface对象。Surface是用来代表图片的pygame对象,可以对一个Surface对象进行涂画、变形、复制等各种操作。事实上,屏幕也只是一个Surfacepygame.display.set_mode()就返回了一个屏幕Surface对象。如果将ball这个Surface对象画到screen Surface 对象,需要使用blit()方法,最后使用display模块的flip()方法更新整个待显示的Surface对象到屏幕上。

  • Surface对象的常用方法

方法名 功能
pygame.Surface.blit() 将一个图像画到另一个图像上
pygame.Surface.convert() 转换图像的像素格式
pygame.Surface.convert_alpha() 转化图像的像素格式,包含alpha通道的转换
pygame.Surface.fill() 使用颜色填充Surface
pygame.Surface.get_rect() 获取Surface的矩形区域
  • 移动图片

    • 下面让小球动起来,ball.get_rect()方法返回值ballrect是一个Rect对象,该对象有一个move()方法可以用于移动矩形。move(x, y)函数有两个参数,第一个参数是 X 轴移动的距离,第二个参数是 Y 轴移动的距离。窗口的左上角是(0, 0),如果是move(100, 50)就是左移100下移50。

    • 为实现小球不停移动,将move()函数添加到while循环内,具体代码如下:

      import pygame
      import sys
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      speed = [5, 5]  # 设置移动的X轴、Y轴
      while True:  # 死循环确保窗口一直显示
         for event in pygame.event.get():  # 遍历所有事件
             if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                 sys.exit()
         ballrect = ballrect.move(speed)  # 移动小球
         screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
         screen.blit(ball, ballrect)  # 将图片画到窗口上
         pygame.display.flip()  # 更新全部显示
      pygame.quit()  # 退出pygame
  • 碰撞检测

    • 运行上述代码,发现小球在屏幕中一闪而过,此时,小球并没有真正消失,而是移动到窗体之外,此时需要添加碰撞检测的功能。当小球与窗体任一边缘发生碰撞,则更改小球的移动方向,具体代码如下:

      import pygame
      import sys
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      speed = [5, 5]  # 设置移动的X轴、Y轴
      while True:  # 死循环确保窗口一直显示
         for event in pygame.event.get():  # 遍历所有事件
             if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                 sys.exit()
                 
         ballrect = ballrect.move(speed)  # 移动小球
         # 碰到左右边缘
         if ballrect.left < 0 or ballrect.right > width:
             speed[0] = -speed[0]
         # 碰到上下边缘
         if ballrect.top < 0 or ballrect.bottom > height:
             speed[1] = -speed[1]
         screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
         screen.blit(ball, ballrect)  # 将图片画到窗口上
         pygame.display.flip()  # 更新全部显示
      pygame.quit()  # 退出pyga                          me

      上述代码中,添加了碰撞检测功能。如果碰到左右边缘,更改X轴数据为负数,如果碰到上下边缘,更改Y轴数据为负数。

  • 限制移动速度

    • 运行上述代码看似有很多球,这是因为运行上述代码的时间非常短,运行快的错觉,使用pygame的time模块,使用pygame时钟之前,必须先创建Clock对象的一个实例,然后在while循环中设置多长时间运行一次。

      import pygame
      import sys
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      speed = [5, 5]  # 设置移动的X轴、Y轴
      clock = pygame.time.Clock()  # 设置时钟
      while True:  # 死循环确保窗口一直显示
         clock.tick(60)  # 每秒执行60次
         for event in pygame.event.get():  # 遍历所有事件
             if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                 sys.exit()
         ballrect = ballrect.move(speed)  # 移动小球
         # 碰到左右边缘
         if ballrect.left < 0 or ballrect.right > width:
             speed[0] = -speed[0]
         # 碰到上下边缘
         if ballrect.top < 0 or ballrect.bottom > height:
             speed[1] = -speed[1]
         screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
         screen.blit(ball, ballrect)  # 将图片画到窗口上
         pygame.display.flip()  # 更新全部显示
      pygame.quit()  # 退出pygame
  • 开发Flappy Bird游戏

    • Flappy Bird是一款鸟类飞行游戏,一根手指操控按下小鸟上飞。

    • 分析 在Flappy Bird游戏中,主要有两个对象:小鸟、管道。可以创建Brid类和Pineline类来分别表示这两个对象。小鸟可以通过上下移动来躲避管道,所以在Brid类中创建一个bridUpdate()方法,实现小鸟的上下移动,为了体现小鸟向前飞行的特征,可以让管道一直向左侧移动,这样在窗口中就好像小鸟在向前飞行。所以在Pineline类中也创建一个updatePipeline()方法,实现管道的向左侧移动。此外还创建了3个函数:createMap()函数用于绘制地图;checkDead()函数用于判断小鸟的生命状态;getResult()函数用于获取最终分数。最后在主逻辑中实例化并调用相关方法,实现相应的功能。

  • 搭建主框架

    # -*- coding:utf-8 -*-
    import sys  # 导入sys模块
    import pygame  # 导入pygame模块
    import random
    class Bird(object):
       """定义一个鸟类"""
       def __init__(self):
           """定义初始化方法"""
           pass
       def birdUpdate(self):
           pass
    class Pipeline(object):
       """定义一个管道类"""
       def __init__(self):
           """定义初始化方法"""
       def updatePipeline(self):
           """水平移动"""
    def createMap():
       """定义创建地图的方法"""
       screen.fill((255, 255, 255))  # 填充颜色(screen还没定义不要着急)
       screen.blit(background, (0, 0))  # 填入到背景
       pygame.display.update()  # 更新显示
    if __name__ == '__main__':
       pygame.init()                           # 初始化pygame
       size = width, height = 400, 650         # 设置窗口大小
       screen = pygame.display.set_mode(size)  # 显示窗口
       clock = pygame.time.Clock()             # 设置时钟
       Pipeline = Pipeline()                   # 实例化管道类
       while True:
           clock.tick(60)                      # 每秒执行60次
           # 轮询事件
           for event in pygame.event.get():
               if event.type == pygame.QUIT:   # 如果检测到事件是关闭窗口
                   sys.exit()
           background = pygame.image.load("assets/background.png")  # 加载背景图片
           createMap()
       pygame.quit()  # 退出

    创建小鸟类、创建管道类、计算得分、碰撞检测

    import pygame
    import sys
    import random
    class Bird(object):
       """定义一个鸟类"""
       def __init__(self):
           """定义初始化方法"""
           self.birdRect = pygame.Rect(65, 50, 50, 50)  # 鸟的矩形
           # 定义鸟的3种状态列表
           self.birdStatus = [pygame.image.load("assets/1.png"),
                              pygame.image.load("assets/2.png"),
                              pygame.image.load("assets/dead.png")]
           self.status = 0      # 默认飞行状态
           self.birdX = 120     # 鸟所在X轴坐标,即是向右飞行的速度
           self.birdY = 350     # 鸟所在Y轴坐标,即上下飞行高度
           self.jump = False    # 默认情况小鸟自动降落
           self.jumpSpeed = 10  # 跳跃高度
           self.gravity = 5     # 重力
           self.dead = False    # 默认小鸟生命状态为活着
       def birdUpdate(self):
           if self.jump:
               # 小鸟跳跃
               self.jumpSpeed -= 1           # 速度递减,上升越来越慢
               self.birdY -= self.jumpSpeed  # 鸟Y轴坐标减小,小鸟上升
           else:
               # 小鸟坠落
               self.gravity += 0.2           # 重力递增,下降越来越快
               self.birdY += self.gravity    # 鸟Y轴坐标增加,小鸟下降
           self.birdRect[1] = self.birdY     # 更改Y轴位置
    class Pipeline(object):
       """定义一个管道类"""
       def __init__(self):
           """定义初始化方法"""
           self.wallx = 400  # 管道所在X轴坐标
           self.pineUp = pygame.image.load("assets/top.png")
           self.pineDown = pygame.image.load("assets/bottom.png")
       def updatePipeline(self):
           """"管道移动方法"""
           self.wallx -= 5  # 管道X轴坐标递减,即管道向左移动
           # 当管道运行到一定位置,即小鸟飞越管道,分数加1,并且重置管道
           if self.wallx < -80:
               global score
               score += 1
               self.wallx = 400
    def createMap():
       """定义创建地图的方法"""
       screen.fill((255, 255, 255))     # 填充颜色
       screen.blit(background, (0, 0))  # 填入到背景
       # 显示管道
       screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300))   # 上管道坐标位置
       screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))  # 下管道坐标位置
       Pipeline.updatePipeline()  # 管道移动
       # 显示小鸟
       if Bird.dead:              # 撞管道状态
           Bird.status = 2
       elif Bird.jump:            # 起飞状态
           Bird.status = 1
       screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY))              # 设置小鸟的坐标
       Bird.birdUpdate()          # 鸟移动
       # 显示分数
       screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50))  # 设置颜色及坐标位置
       pygame.display.update()    # 更新显示
    def checkDead():
       # 上方管子的矩形位置
       upRect = pygame.Rect(Pipeline.wallx, -300,
                            Pipeline.pineUp.get_width() - 10,
                            Pipeline.pineUp.get_height())
       # 下方管子的矩形位置
       downRect = pygame.Rect(Pipeline.wallx, 500,
                              Pipeline.pineDown.get_width() - 10,
                              Pipeline.pineDown.get_height())
       # 检测小鸟与上下方管子是否碰撞
       if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
           Bird.dead = True
       # 检测小鸟是否飞出上下边界
       if not 0 < Bird.birdRect[1] < height:
           Bird.dead = True
           return True
       else:
           return False
    def getResutl():
       final_text1 = "Game Over"
       final_text2 = "Your final score is: " + str(score)
       ft1_font = pygame.font.SysFont("Arial", 70)                                      # 设置第一行文字字体
       ft1_surf = font.render(final_text1, 1, (242, 3, 36))                             # 设置第一行文字颜色
       ft2_font = pygame.font.SysFont("Arial", 50)                                      # 设置第二行文字字体
       ft2_surf = font.render(final_text2, 1, (253, 177, 6))                            # 设置第二行文字颜色
       screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100])  # 设置第一行文字显示位置
       screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200])  # 设置第二行文字显示位置
       pygame.display.flip()                                                            # 更新整个待显示的Surface对象到屏幕上
    if __name__ == '__main__':
       """主程序"""
       pygame.init()                            # 初始化pygame
       pygame.font.init()                       # 初始化字体
       font = pygame.font.SysFont("Arial", 50)  # 设置字体和大小
       size = width, height = 400, 650          # 设置窗口
       screen = pygame.display.set_mode(size)   # 显示窗口
       clock = pygame.time.Clock()              # 设置时钟
       Pipeline = Pipeline()                    # 实例化管道类
       Bird = Bird()                            # 实例化鸟类
       score = 0
       while True:
           clock.tick(60)                       # 每秒执行60次
           # 轮询事件
           for event in pygame.event.get():
               if event.type == pygame.QUIT:
                   sys.exit()
               if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
                   Bird.jump = True             # 跳跃
                   Bird.gravity = 5             # 重力
                   Bird.jumpSpeed = 10          # 跳跃速度
           background = pygame.image.load("assets/background.png")  # 加载背景图片
           if checkDead():                      # 检测小鸟生命状态
               getResutl()                      # 如果小鸟死亡,显示游戏总分数
           else:
               createMap()                      # 创建地图
       pygame.quit()
    import pygame import sys pygame.init()* # 初始化pygame*
    size = width, height =320,240* # 设置窗口大小*
    screen = pygame.display.set_mode(size)* # 显示窗口*
    whileTrue:* # 死循环确保窗口一直显示*
       for event in pygame.event.get():*# 遍历所有事件*
           if event.type== pygame.QUIT:*# 如果单击关闭窗口,则退出*
               sys.exit()
               pygame.quit()*  # 退出pygame*

random

  1. 常用功能

    random.random() # 返回随机生成的一个浮点数,范围在[0,1)之间
    random.uniform(minNumber, maxNumber) # 返回随机生成的一个浮点数,范围在[minNumber, maxNumber)之间
    random.randint(minNumber, maxNumber) # 生成指定范围内的整数
    random.randrange([start],stop[,step]) # 用于从指定范围内按指定基数递增的集合中获取一个随机数。
    random.choice() # 从指定的序列中获取一个随机元素
    random.shuffle(x[,random]) # 用于将一个列表中的元素打乱,随机排序
    random.sample(sequence,k) # 用于从指定序列中随机获取指定长度的片段,sample()函数不会修改原有序列。
    np.random.rand(d0, d1, …, dn) # 返回一个或一组浮点数,范围在[0, 1)之间
    np.random.normal(loc=a, scale=b, size=()) # 返回满足条件为均值=a, 标准差=b的正态分布(高斯分布)的概率密度随机数
    np.random.randn(d0, d1, … dn) # 返回标准正态分布(均值=0,标准差=1)的概率密度随机数
    np.random.standard_normal(size=()) # 返回标准正态分布(均值=0,标准差=1)的概率密度随机数
    np.random.randint(a, b, size=(), dtype=int) # 返回在范围在[a, b)中的随机整数(含有重复值)
    random.seed() # 设定随机种子

time

  1. time.time(),表示当前时间的时间戳,常用语计算一段代码的运行时间

  2. time.localtime(),将一个时间戳转换为当前时区的struct_time,其可以直接通过索引或者是使用成员符号取相关值。

  3. time.gmtime(),将一个时间戳转换为UTC时区的struct_time。

  4. time.mktime(),将struct_time转换成时间戳

  5. time.sleep(),线程睡眠指定时间,这块不做实际演示了,相信大家在写爬虫时候也遇到过,至少博主最开始使用time模块的第一个方法就是.sleep()

  6. time.clock(),函数以浮点数计算的秒数返回当前的CPU时间,其中:在NUix系统上,它返回的是“进程时间”,它是用妙表示的浮点数(时间戳)。在Windows中,第一次调用,返回的是进程运行时实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。

  7. time.asctime(),把一个表示时间的元组或者struct_time表示为 Fri Aug 28 16:23:17 2020 这种形式

  8. time.ctime(),把一个时间戳表示为 Sun Aug 23 14:31:59 2015’ 这种形式

  9. time.strftime( format [, t] ),把一个代表时间的元组或者struct_time转化为格式化的时间字符串,格式由参数format决定。

    1. 其中format为时间字符串的格式化样式,t为struct_time形式的参数,format格式如下:

      - %y 两位数的年份表示(00-99)
      - %Y 四位数的年份表示(000-9999)
      - %m 月份(01-12)
      - %d 月内中的一天(0-31)
      - %H 24小时制小时数(0-23)
      - %I 12小时制小时数(01-12)
      - %M 分钟数(00-59)
      - %S 秒(00-59)
      - %a 本地简化星期名称
      - %A 本地完整星期名称
      - %b 本地简化的月份名称
      - %B 本地完整的月份名称
      - %c 本地相应的日期表示和时间表示
      - %j 年内的一天(001-366)
      - %p 本地A.M.或P.M.的等价符
      - %U 一年中的星期数(00-53)星期天为星期的开始
      - %w 星期(0-6),星期天为星期的开始
      - %W 一年中的星期数(00-53)星期一为星期的开始
      - %x 本地相应的日期表示
      - %X 本地相应的时间表示
      - %Z 当前时区的名称
      - %% %号本身
  10. time.strptime(string[,format]),将格式字符串转化成struct_time. 该函数是time.strftime()函数的逆操作。

  11. 注:在使用strptime()函数将一个指定格式的时间字符串转化成元组时,参数format的格式必须和string的格式保持一致,如果string中日期间使用“-”分隔,format中也必须使用“-”分隔,时间中使用冒号“:”分隔,后面也必须使用冒号分隔,否则会报格式不匹配的错误。

IPython.display

  1. 本文整理汇总了Python中IPython.display*方法*的典型用法代码示例。如果您正苦于以下问题:Python IPython.display方法的具体用法?Python IPython.display怎么用?Python IPython.display使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IPython的用法示例。

  2. 在下文中一共展示了IPython.display方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

  3. display_images

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_images(images, titles=None, cols=4, cmap=None, norm=None,
                      interpolation=None):
       """Display the given set of images, optionally with titles.
      images: list or array of image tensors in HWC format.
      titles: optional. A list of titles to display with each image.
      cols: number of images per row
      cmap: Optional. Color map to use. For example, "Blues".
      norm: Optional. A Normalize instance to map values to colors.
      interpolation: Optional. Image interpolation to use for display.
      """
       titles = titles if titles is not None else [""] * len(images)
       rows = len(images) // cols + 1
       plt.figure(figsize=(14, 14 * rows // cols))
       i = 1
       for image, title in zip(images, titles):
           plt.subplot(rows, cols, i)
           plt.title(title, fontsize=9)
           plt.axis('off')
           plt.imshow(image.astype(np.uint8), cmap=cmap,
                      norm=norm, interpolation=interpolation)
           i += 1
       plt.show()
  4. display_alert

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_alert(
       alert: Union[Mapping[str, Any], SecurityAlert], show_entities: bool = False
    ):
       """
      Display a Security Alert.
      Parameters
      ----------
      alert : Union[Mapping[str, Any], SecurityAlert]
          The alert to display as Mapping (e.g. pd.Series)
          or SecurityAlert
      show_entities : bool, optional
          Whether to display entities (the default is False)
      """
       output = format_alert(alert, show_entities)
       if not isinstance(output, tuple):
           output = [output]
       for disp_obj in output:
           display(disp_obj)
  5. display_process_tree

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_process_tree(process_tree: pd.DataFrame):
       """
      Display process tree data frame. (Deprecated).
      Parameters
      ----------
      process_tree : pd.DataFrame
          Process tree DataFrame
      The display module expects the columns NodeRole and Level to
      be populated. NoteRole is one of: 'source', 'parent', 'child'
      or 'sibling'. Level indicates the 'hop' distance from the 'source'
      node.
      """
       build_and_show_process_tree(process_tree)
  6. display_logon_data

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_logon_data(
       logon_event: pd.DataFrame, alert: SecurityAlert = None, os_family: str = None
    ):
       """
      Display logon data for one or more events as HTML table.
      Parameters
      ----------
      logon_event : pd.DataFrame
          Dataframe containing one or more logon events
      alert : SecurityAlert, optional
          obtain os_family from the security alert
          (the default is None)
      os_family : str, optional
            explicitly specify os_family (Linux or Windows)
            (the default is None)
      Notes
      -----
      Currently only Windows Logon events.
      """
       display(format_logon(logon_event, alert, os_family))
  7. post_execute

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def post_execute(self):
           if self.isFirstPostExecute:
               self.isFirstPostExecute = False
               self.isFirstPreExecute = False
               return 0
           self.flag = False
           self.asyncCapturer.Wait()
           self.ioHandler.Poll()
           self.ioHandler.EndCapture()
           # Print for the notebook
           out = self.ioHandler.GetStdout()
           err = self.ioHandler.GetStderr()
           if not transformers:
               sys.stdout.write(out)
               sys.stderr.write(err)
           else:
               for t in transformers:
                  (out, err, otype) = t(out, err)
                   if otype == 'html':
                       IPython.display.display(HTML(out))
                       IPython.display.display(HTML(err))
           return 0
  8. display_images

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_images(images, titles=None, cols=4, cmap=None, norm=None,
                      interpolation=None):
       """Display the given set of images, optionally with titles.
      images: list or array of image tensors in HWC format.
      titles: optional. A list of titles to display with each image.
      cols: number of images per row
      cmap: Optional. Color map to use. For example, "Blues".
      norm: Optional. A Normalize instance to map values to colors.
      interpolation: Optional. Image interporlation to use for display.
      """
       titles = titles if titles is not None else [""] * len(images)
       rows = len(images) // cols + 1
       plt.figure(figsize=(14, 14 * rows // cols))
       i = 1
       for image, title in zip(images, titles):
           plt.subplot(rows, cols, i)
           plt.title(title, fontsize=9)
           plt.axis('off')
           plt.imshow(image.astype(np.uint8), cmap=cmap,
                      norm=norm, interpolation=interpolation)
           i += 1
       plt.show()
  9. check_render_options

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def check_render_options(**options):
       """
      Context manager that will assert that alt.renderers.options are equivalent
      to the given options in the IPython.display.display call
      """
       import IPython.display
       def check_options(obj):
           assert alt.renderers.options == options
       _display = IPython.display.display
       IPython.display.display = check_options
       try:
           yield
       finally:
           IPython.display.display = _display
  10. register_json_formatter

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def register_json_formatter(cls: Type, to_dict_method_name: str = 'to_dict'):
       """
      TODO
      :param cls:
      :param to_dict_method_name:
      :return:
      """
       if not hasattr(cls, to_dict_method_name) or not callable(getattr(cls, to_dict_method_name)):
           raise ValueError(f'{cls} must define a {to_dict_method_name}() method')
       try:
           import IPython
           import IPython.display
           if IPython.get_ipython() is not None:
               def obj_to_dict(obj):
                   return getattr(obj, to_dict_method_name)()
               ipy_formatter = IPython.get_ipython().display_formatter.formatters['application/json']
               ipy_formatter.for_type(cls, obj_to_dict)
       except ImportError:
           pass
  11. render

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def render(obj, **kwargs):
       info = process_object(obj)
       if info:
           display(HTML(info))
           return
       if render_anim is not None:
           return render_anim(obj)
       backend = Store.current_backend
       renderer = Store.renderers[backend]
       # Drop back to png if pdf selected, notebook PDF rendering is buggy
       if renderer.fig == 'pdf':
           renderer = renderer.instance(fig='png')
       return renderer.components(obj, **kwargs)
  12. image_display

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def image_display(element, max_frames, fmt):
       """
      Used to render elements to an image format (svg or png) if requested
      in the display formats.
      """
       if fmt not in Store.display_formats:
           return None
       info = process_object(element)
       if info:
           display(HTML(info))
           return
       backend = Store.current_backend
       if type(element) not in Store.registry[backend]:
           return None
       renderer = Store.renderers[backend]
       plot = renderer.get_plot(element)
       # Current renderer does not support the image format
       if fmt not in renderer.param.objects('existing')['fig'].objects:
           return None
       data, info = renderer(plot, fmt=fmt)
       return {info['mime_type']: data}, {}
  13. wait_for_import

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def wait_for_import(self, count, timeout=300):
           time_start = time.time()
           while time.time() < time_start + timeout:
               t = self.client.table(self.database, self.table)
               self.imported_count = t.count - self.initial_count
               if self.imported_count >= count:
                   break
               self._display_progress(self.frame_size)
               time.sleep(2)
           # import finished
           self.imported_at = datetime.datetime.utcnow().replace(microsecond=0)
           # import timeout
           if self.imported_count < count:
               self.import_timeout = timeout
           self._display_progress(self.frame_size)
           # clear progress
           if self.clear_progress and self.imported_count == count:
               IPython.display.clear_output()
    # public methods
  14. display_images

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_images(images, titles=None, cols=4, cmap=None, norm=None,
                      interpolation=None):
       """Display the given set of images, optionally with titles.
      images: list or array of image tensors in HWC format.
      titles: optional. A list of titles to display with each image.
      cols: number of images per row
      cmap: Optional. Color map to use. For example, "Blues".
      norm: Optional. A Normalize instance to map values to colors.
      interpolation: Optional. Image interporlation to use for display.
      """
       titles = titles if titles is not None else [""] * len(images)
       rows = len(images) // cols + 1
       plt.figure(figsize=(14, 14 * rows // cols))
       i = 1
       for image, title in zip(images, titles):
           plt.subplot(rows, cols, i)
           plt.title(title, fontsize=9)
           plt.axis('off')
           plot_area = image[:,:,0] if len(image.shape) == 3 else image
           plt.imshow(plot_area.astype(np.uint8), cmap=cmap,
                      norm=norm, interpolation=interpolation)
           i += 1
       plt.show()
  15. display_table

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def display_table(table):
       """Display values in a table format.
      table: an iterable of rows, and each row is an iterable of values.
      """
       html = ""
       for row in table:
           row_html = ""
           for col in row:
               row_html += "<td>{:40}</td>".format(str(col))
           html += "<tr>" + row_html + "</tr>"
       html = "<table>" + html + "</table>"
       IPython.display.display(IPython.display.HTML(html))
  16. format_alert

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def format_alert(
       alert: Union[Mapping[str, Any], SecurityAlert], show_entities: bool = False
    ) -> Union[IPython.display.HTML, Tuple[IPython.display.HTML, pd.DataFrame]]:
       """
      Get IPython displayable Security Alert.
      Parameters
      ----------
      alert : Union[Mapping[str, Any], SecurityAlert]
          The alert to display as Mapping (e.g. pd.Series)
          or SecurityAlert
      show_entities : bool, optional
          Whether to display entities (the default is False)
      Returns
      -------
      Union[IPython.display.HTML, Tuple[IPython.display.HTML, pd.DataFrame]]
          Single or tuple of displayable IPython objects
      Raises
      ------
      ValueError
          If the alert object is in an unknown format
      """
       if isinstance(alert, SecurityAlert):
           return HTML(alert.to_html(show_entities=show_entities))
       # Display subset of raw properties
       if isinstance(alert, pd.Series):
           entity = alert["CompromisedEntity"] if "CompromisedEntity" in alert else ""
           title = f"""
              <h3>Series Alert: '{alert["AlertDisplayName"]}'</h3>
              <b>Alert_time:</b> {alert["StartTimeUtc"]},&nbsp;
              <b>Compr_entity:</b> {entity},&nbsp;
              <b>Alert_id:</b> {alert["SystemAlertId"]}
              <br/>
              """
           return HTML(title), pd.DataFrame(alert)
       raise ValueError("Unrecognized alert object type " + str(type(alert)))
  17. to_notebook

    # 需要导入模块: import IPython [as 别名]
    # 或者: from IPython import display [as 别名]
    def to_notebook(self, transparent_bg=True, scale=(1, 1)):
           # if not in_notebook():
           #     raise ValueError("Cannot find notebook.")
           wimg = self._win2img(transparent_bg, scale)
           writer = BSPNGWriter(writeToMemory=True)
           result = serial_connect(wimg, writer, as_data=False).result
           data = memoryview(result).tobytes()
           from IPython.display import Image
           return Image(data)

tqdm

  1. 有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事。

  2. tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况,等进度展示。

  3. tqdm安装:pip install tqdm

  4. 用tqdm子模块,对于可以迭代的对象都可以使用下面这种方式,来实现可视化进度,非常方便。

    from tqdm import tqdm
    import time
    for i in tqdm(range(100)):
       time.sleep(0.1)
       pass
    d ={'loss':0.2,'learn':0.8}
    for i in tqdm(range(50),desc='进行中',ncols=10,postfix=d):
    # desc设置名称,ncols设置进度条长度.postfix以字典形式传入详细信息
       time.sleep(0.1)
       pass
    # 通过**tqdm**提供的`set_description`方法可以实时查看每次处理的数据
    pbar = tqdm(["a","b","c","d"])
    for c in pbar:
       time.sleep(1)
       pbar.set_description("Processing %s" %c)
  5. 用trange子模块,效果和用tqdm子模块一样

    from tqdm import tqdm
    import time
    for i in trange( 100):
       time.sleep(0.1)
       pass
  6. 手动设置处理进度

    from tqdm import tqdm
    import time
    # total参数设置进度条的总长度
    with tqdm(total=100) as bar: # total表示预期的迭代次数
       for i in range(100): # 同上total值
           time.sleep(0.1)
           bar.update(1) # 每次更新进度条的长度

积分系统

1.Python代码

import pymysql
import easygui
import mysql_function
class INTEGRAL_FUNCTOIN ():
   
  def __init__ (self,MYSQL):                                                   #自动执行打开封装mysql
      self.conn = pymysql.connect(host="localhost",user="root",password="1451964253",database="优惠记录")
      self.cursor = self.conn.cursor()
      self.print_condition = {"1":self.integral_query,"2":self.integral_join,"3":self.user_join,"4":self.satisfy_modify_if}
      self.MYSQL = MYSQL.mysql
       
  def integral_query(self):                                               #获得姓名进行查找
      while True:
          message = ['姓名']
          name = student = easygui.multenterbox('查询积分:', '积分系统', message)
          if None == name:
              break
          self.cursor.execute(self.MYSQL["QUERY"],name)
          result = self.cursor.fetchone()
          if result == None:
              easygui.msgbox("暂未有几分",'积分查询','Yes')
              continue
          else:
              print_ = ",".join(result[:-1]),",积分:",str(result[-1])
              easygui.msgbox(print_,'积分查询','Yes')
               
  def integral_join(self):                                               #加入积分,输入积分和姓名添加到mysql中
      while True:
          message = ['姓名',"积分"]
          name = student = easygui.multenterbox('添加积分:', '积分系统', message)
          if None == name:
              break
          try:
              r = self.cursor.execute(self.MYSQL["JOIN_INTEGRAL"],[name[1],name[0]])
              self.conn.commit()
          except Exception:
              easygui.msgbox("没有该用户!",'积分查询','Yes')
  def user_join(self):                                                   #用户添加如果有新用户,就可以加入
      while True:
          message = ['姓名',"电话"]
          name = student = easygui.multenterbox('添加用户:', '积分系统', message)
          if None == name:
              break
          self.cursor.execute(self.MYSQL["USER_QUERY"],[name[0],name[1]])           #调出判断是否存在此用户
          result = self.cursor.fetchone()
          try:
              if name[0] == result[0]:
                  easygui.msgbox("用户以存在!",'添加用户','Yes')
          except Exception:
              r = self.cursor.execute(self.MYSQL["JOIN_USER"],[name[0],name[1]]) #不存在再添加
              self.conn.commit()
              easygui.msgbox("用户以添加",'添加用户','Yes')
                   
  def satisfy_modify_if (self):
      while True:
          message = ['姓名']
          name = student = easygui.multenterbox('输入姓名后即可删除!', '积分系统', message)
          if None == name:
              break                                             #大于就让他清零
          easygui.msgbox("恭喜你你的积分",'满足查询','Yes')
          self.cursor.execute(self.MYSQL["DELETE"] ,[name])  
          self.conn.commit()          
          easygui.msgbox("已清理",'添加用户','Yes')
               
  def mysql_sign_in (self,alias):             #判断进入
      self.print_condition[alias]()
      self.cursor.close()  
      self.conn.close()
while True:
  tuple = ('1','2','3',"4")
  command = easygui.buttonbox("""查看信息请按:1\n添加记录请按:2\n添加用户请按:3\n条件满足的数据:4""",'积分系统',tuple)
  if command == None:
      break
  obj = INTEGRAL_FUNCTOIN(mysql_function)
  obj.mysql_sign_in(command)

2.自定文件 mysql_function

 

mysql = {"QUERY":"select name,telephone_number,sum(integral) from integral_table left join user_table on integral_table.uid = user_table.user_id where user_table.name =%s group by user_id"
,"DELETE":"update integral_table set integral = 0 where uid = (SELECT user_id FROM user_table WHERE name = %s )"
,"JOIN_INTEGRAL": "insert integral_table (time,integral,uid) values (now(),%s,(select user_id from user_table where name = %s))"
,"USER_QUERY": "select name,telephone_number from user_table where name =%s and telephone_number =%s"
,"JOIN_USER": "insert user_table (name,telephone_number) values (%s,%s)"
,"satisfy_999":"select name ,telephone_number,integral from user_table left join (select uid ,sum(integral) as integral from integral_table group by uid) as number on user_table.user_id = number.uid where number.integral >= 999"}

3.mysql

3.1 用户表

CREATE TABLE `user_table` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`telephone_number` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 26 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

3.2 积分表

CREATE TABLE `integral_table` (
`record_id` int(11) NOT NULL AUTO_INCREMENT,
`time` datetime(0) NOT NULL ON UPDATE CURRENT_TIMESTAMP(0),
`integral` int(255) NULL DEFAULT NULL,
`uid` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`record_id`) USING BTREE,
INDEX `user_link`(`uid`) USING BTREE,
CONSTRAINT `user_link` FOREIGN KEY (`uid`) REFERENCES `user_table` (`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 41 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

 

posted @   無敗の草  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示