栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python自主学习1

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python自主学习1

python自主学习
  • 爬取百度图片
  • 随机产生1000000条成绩记录
  • Access库student.mdb中表student内容如下

爬取百度图片

【题目】
1.根据百度图片库接口url,搜索多页图片链接并下载图片。图片链接用正则表达式表示;接口参数中的搜索关键字、页号和每页图片数用输入参数设置。
2.程序中获取图片文件内容后立即存储到指定文件夹中
3.独立定义搜索的关键字
【源码】

# -*- coding: UTF-8 -*-
import requests
import json
import os
import pprint
# 创建一个文件夹
path = 'C:/python'
if not os.path.exists(path):
    os.mkdir(path)
# 导入一个请求头
header = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}
# 用户输入信息指令
keyword = input('请输入你想下载的内容:')
page = input('请输入你想爬取的页数:')
page = int(page) + 1
n = 0
pn = 1
# pn代表从第几张图片开始获取
for m in range(1, page):
    url = 'https://image.baidu.com/search/acjson?'
    param = {
        'tn': 'resultjson_com',
        'logid': ' 7517080705015306512',
        'ipn': 'rj',
        'ct': '201326592',
        'is': '',
        'fp': 'result',
        'queryWord': keyword,
        'cl': '2',
        'lm': '-1',
        'ie': 'utf-8',
        'oe': 'utf-8',
        'adpicid': '',
        'st': '',
        'z': '',
        'ic': '',
        'hd': '',
        'latest': '',
        'copyright': '',
        'word': keyword,
        's': '',
        'se': '',
        'tab': '',
        'width': '',
        'height': '',
        'face': '',
        'istype': '',
        'qc': '',
        'nc': '1',
        'fr': '',
        'expermode': '',
        'force': '',
        'cg': 'star',
        'pn': pn,
        'rn': '30',#这里的30可以自己修改
        'gsm': '1e',
    }
    # 定义一个空列表,用于存放图片的URL
    image_url = list()
    # 将编码形式转换为utf-8
    response = requests.get(url=url, headers=header, params=param)
    response.encoding = 'utf-8'
    response = response.text
    # 把字符串转换成json数据
    data_s = json.loads(response)
    a = data_s["data"]  # 提取data里的数据
    for i in range(len(a)-1):  # 去掉最后一个空数据
        data = a[i].get("thumbURL", "not exist")  # 防止报错key error
        image_url.append(data)

    for image_src in image_url:
        image_data = requests.get(url=image_src, headers=header).content  # 提取图片内容数据
        image_name = '{}'.format(n+1) + '.jpg'  # 图片名
        image_path = path + '/' + image_name  # 图片保存路径
        with open(image_path, 'wb') as f:  # 保存数据
            f.write(image_data)
            print(image_name, '下载成功啦!!')
            f.close()
        n += 1
    pn += 29

【运行结果】

随机产生1000000条成绩记录

【题目】
随机产生1000000条成绩记录,其中包括Python、Java、C三门课程的成绩,编程统计三个分数段(“0-59”, “60-84”, “85-100”)的人数、平均分、方差
【源码】

import pandas
import numpy
import random
#需要自己安装pandas,numpy,random库(在cmd命令窗口下运行命令:pip install 库名)
grade_x = {'python': [random.randint(0, 100) for i in range(1, 100001)],
           'java': [random.randint(0, 100) for i in range(1, 100001)],
           'c': [random.randint(0, 100) for i in range(1, 100001)]}
group_grade = {'python': {"0-59": [], "60-84": [], "85-100": []},
               'java': {"0-59": [], "60-84": [], "85-100": []},
               'c': {"0-59": [], "60-84": [], "85-100": []}}
tongji_x = {"0-59": {'人数': 0, '平均分': 0, '方差': 0},
            "60-84": {'人数': 0, '平均分': 0, '方差': 0},
            "85-100": {'人数': 0, '平均分': 0, '方差': 0}}


grade = pandas.Dataframe(grade_x)
group = pandas.Dataframe(group_grade)
tj = pandas.Dataframe(tongji_x)

# print(group)


for key in grade:
    # print(key)  # 课程名
    group[key]["0-59"] = grade[(0 <= grade[key]) & (grade[key] < 60)][[key]]
    #        (0 <= grade[key]) & (grade[key] <= 59)  其中()是必须的,多行索引使用两个中括号:[[x]]
    group[key]["60-84"] = grade[(60 <= grade[key]) & (grade[key] < 85)][[key]]
    group[key]["85-100"] = grade[(85 <= grade[key]) & (grade[key] <= 100)][[key]]

# print(group)

filename = r"随机成绩.txt"  # 首先创建一个 .txt 文件
with open(filename, "w+") as file:  # 用with as 方法打开写入
    file.write(str(grade) + 'n')  # 换行输入到文件中

    for key in group:
        # print(key)  # 课名
        for key1 in tongji_x:
            # print(key1)  # 区间
            tj[key1]["人数"] = group[key][key1].count()  # 人数
            tj[key1]["平均分"] = numpy.mean(group[key][key1])  # 平均分
            tj[key1]["方差"] = numpy.var(group[key][key1])  # 方差

        file.write(str(key) + 'n' + str(tj) + 'n')  # 换行输入到文件中
        print(key, 'n', tj, 'n')

【运行结果】

Access库student.mdb中表student内容如下

【题目】
Access库student.mdb中表student内容如下:
1001 王萍 女 软件工程
1002 李明 男 软件工程
1003 顾于 女 软件工程
2001 张胜 男 计算机科学
2002 宋佳 男 计算机科学
2003 谢芳 女 计算机科学
如有不一致的数据,请修改。
编程:
(1)增加记录:2004 好好 女 软件工程
(2)增加记录:2005 好好 男 计算机科学
(3)修改 :顾于的class为计算机科学
(4)删除:sid为2005的记录
(5)输出所有男生记录
(6)输出class为软件工程的女生记录
【源码】

import pypyodbc#需要自己安装pypyodbc库
path = 'd:\student.mdb'#这个是自己创建的access数据库的路径
conn = pypyodbc.connect(r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + path + ";Uid=;Pwd=;")#连接数据库
cursor = conn.cursor()
SQL_value = 'select * from student'
for row in cursor.execute(SQL_value):
    print(row)
#添加
add_field_SQL1= '''insert into student (sid,name,sex,class) values ('2004','好好','女','软件工程')''' 
add_field_SQL2= '''insert into student (sid,name,sex,class) values ('2005','好好','男','计算机科学')''' 
cursor.execute(add_field_SQL1)
cursor.execute(add_field_SQL2)
cursor.commit()
#删除
sql1="DELETe * FROM student WHERe sid=2005"
cursor.execute(sql1)
cursor.commit()
#修改
sql2="UPDATe student SET class='计算机科学' WHERe name='顾于'"
cursor.execute(sql2)
cursor.commit()
#查询男生
sql3="SELECT *FROM student WHERe sex='男'"#sql语句
cursor.execute(sql3)
result1=cursor.fetchall()
for row in result1:
	for col in range(len(row)):
		print(row[col],"t",end="")
	print("")
#查询class中的女生记录
sql4="SELECt *FROM student WHERe class='软件工程' AND sex='女'"
cursor.execute(sql4)
result2=cursor.fetchall()
for row in result2:
	for col in range(len(row)):
		print(row[col],"t",end="")
	print("")
#输出数据库
for row in cursor.execute(SQL_value):
    print(row)
conn.close()

【注意】
运行此代码需要添加数据源
如何添加数据源请看这个文章:
如何添加数据源
需要下载驱动
Access驱动官方驱动下载
【运行结果】

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675255.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号