【paddlepaddle】《百度深度学习7日打卡营-Python小白逆袭AI大神》学习心得

课程宣传先上:https://aistudio.baidu.com/aistudio/course/introduce/1224

在参加这期训练营之前,了解过PaddlePaddle,但是没有深度去了解他,后面通过PaddlePaddle官网发现了AIStudio。就开始在AIStudio上学习相关的课程,也看到了很多往期的七天打卡营,自己认为自己不是一个学习比较自觉地人,所以一直想要参加打卡营,这样会给自己一个动力和约束。最后终于发现了这个打卡营。(这就是我与打卡营的相似)

【心得体会】

七天的课程安排很合理,基本是阶梯式难度加大,比如最后的大作业,看着挺难,但是在开始前授课老师会提供思路。然后课后自己集合之前的学习内容就可以去尝试。

核心思想:

重点还是在于自己去摸索,七天打卡营最要是去做一个引导,自己可以通过课程这个点去扩散开来,自己去学习到相关的内容。这样就可以把七天的学习内容扩散到一定大的知识面。

核心态度:

每天按时参加在线直播课,在线直播课会让自己有很强的代入感,比自己只看视频要更深刻。

坚持独立自主的完成作业,通过每天的课程学习,然后自己通过CSDN、以及AIStudio等平台找到类似的案例。通过案例的学习,举一反三,来解决自己的问题。

学会写高质量的代码,在大家学习案例时,可能会懊恼一些只提供代码没有注释的案例,看着头大。

学会写博客分享自己的代码、学习的内容和想法。大家都会觉得博客是大佬写给小白看的内容,我觉得作为小白更应该写自己的学习内容,那样在你自己以后遇到同样的问题,能够快速的解决自己的问题(类似于读书时的错题本)。

Class Start:

第一天:

def day1_1():
    '''
    第一天主要是乘法口诀表和文件查找
    作为一个Python小白和很久没写代码的菜鸟
    弄了比较多的笑话不过最终实现了需求“Accept”
    :return:
    '''

    ### 乘法口诀表 ###
    # demo
    # 在这里我没有考虑到使用'\t'来达到将输出排列对齐
    # 所以增加了elif等多余的代码。
    for i in range(1, 10):
        for j in range(1, i + 1):
            # i 等于 j 时换行
            if i == j:
                print('%d*%d=%d' % (j, i, i * j), end='\n')
            # 保持积为一位与两位的垂直排序
            elif i * j < 10 and j != 1:
                print('%d*%d=%d' % (j, i, i * j), end='   ')
            else:
                print('%d*%d=%d' % (j, i, i * j), end='  ')

    # Teacher
    for i in range(1, 10):
        for j in range(1, i + 1):
            print('%d*%d=%d' % (j, i, i * j), end='\t')
        print()


    ### 文件查找 ###
# 导入OS模块
import os




def day1_2():
    '''
    文件查找主要涉及的就是关于Python3 OS 文件/目录方法
    通过自己的学习相关文档可以学到自己想要的。
    笔者是在菜鸟教程上学习
    菜鸟教程:https://www.runoob.com/
    注释的两个版本代码是在初步摸索(根本没仔细看文档)
    不过,同样让我了解了os.walk() 返回值是什么结构。
    个人觉得小白还是可以做一些盲目的尝试,这样也可以通过思考多去撸撸代码。
    :return:
    '''
    # 待搜索的目录路径
    path = "Day1-homework"
    # 待搜索的名称
    filename = "2020"
    # 定义保存结果的数组
    result = []
    # 在这里写下您的查找文件代码吧!
    for root, dirs, files in os.walk(path, topdown=False):
        for name in files:
            if filename in name:
                result.append(os.path.join(root, name))
    for j in range(len(result)):
        print("编号:%d 路径:'%s'" % (j + 1, result[j]))

    # for file_path in os.walk(path):
    #     #print(file_path)
    #     file_tmp = file_path[2]
    #     for i in range(len( file_path[2])):
    #         if filename in file_path[2][i]:
    #            # path_temp = file_path[2]+(file_tmp[i])
    #            # print(path_temp)
    #             path_temp = file_path[0] + '/' +  file_path[2][i]
    #             result.append(path_temp)
    # for j in range(len(result)):
    #     print('编号:%d 路径:%s'%(j+1,result[j]))

    # j = 0
    # for file_path in os.walk(path):
    #     for i in range(len(file_path[2])):
    #         if filename in file_path[2][i]:
    #             j += 1
    #             path_temp = file_path[0] + '/' + file_path[2][i]
    #             result.append(path_temp)
    #             print("编号:%d 路径:'%s'" % (j, path_temp))

第二天

任务Day2-《青春有你2》选手信息爬取

作业链接:https://aistudio.baidu.com/aistudio/projectdetail/422353

request模块:

requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/

requests.get(url)可以发送一个http get请求,返回服务器响应内容。

 

BeautifulSoup库:

BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库。网址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml。

BeautifulSoup(markup, "html.parser")或者BeautifulSoup(markup, "lxml"),推荐使用lxml作为解析器,因为效率更高。

 代码走起:

import sys
import json
import re
import requests
import datetime
from bs4 import BeautifulSoup
import os

#获取当天的日期,并进行格式化,用于后面文件命名,格式:20200420
today = datetime.date.today().strftime('%Y%m%d')    

# 一、爬取百度百科中《青春有你2》中所有参赛选手信息,返回页面数据
def crawl_wiki_data():
    """
    爬取百度百科中《青春有你2》中参赛选手信息,返回html
    """
    headers = { 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    url='https://baike.baidu.com/item/青春有你第二季'                         

    try:
        response = requests.get(url,headers=headers)
        print(response.status_code)

        #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
        soup = BeautifulSoup(response.text,'lxml')
        
        #返回的是class为table-view log-set-param的<table>所有标签
        tables = soup.find_all('table',{'class':'table-view log-set-param'})

        crawl_table_title = "参赛学员"

        for table in  tables:           
            #对当前节点前面的标签和字符串进行查找
            table_titles = table.find_previous('div').find_all('h3')
            for title in table_titles:
                if(crawl_table_title in title):
                    return table       
    except Exception as e:
        print(e)

#二、对爬取的页面数据进行解析,并保存为JSON文件
def parse_wiki_data(table_html):
    '''
    从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到work目录下
    '''
    bs = BeautifulSoup(str(table_html),'lxml')
    all_trs = bs.find_all('tr')

    error_list = ['\'','\"']

    stars = []

    for tr in all_trs[1:]:
         all_tds = tr.find_all('td')

         star = {}

         #姓名
         star["name"]=all_tds[0].text
         #个人百度百科链接
         star["link"]= 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
         #籍贯
         star["zone"]=all_tds[1].text
         #星座
         star["constellation"]=all_tds[2].text
         #身高
         star["height"]=all_tds[3].text
         #体重
         star["weight"]= all_tds[4].text

         #花语,去除掉花语中的单引号或双引号
         flower_word = all_tds[5].text
         for c in flower_word:
             if  c in error_list:
                 flower_word=flower_word.replace(c,'')
         star["flower_word"]=flower_word 
         
         #公司
         if not all_tds[6].find('a') is  None:
             star["company"]= all_tds[6].find('a').text
         else:
             star["company"]= all_tds[6].text  

         stars.append(star)

    json_data = json.loads(str(stars).replace("\'","\""))   
    with open('work/' + today + '.json', 'w', encoding='UTF-8') as f:
        json.dump(json_data, f, ensure_ascii=False)
        print('下载成功')
#三、爬取每个选手的百度百科图片,并进行保存
def crawl_pic_urls():
    '''
    爬取每个选手的百度百科图片,并保存
    ''' 
    with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
         json_array = json.loads(file.read())

    headers = { 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' 
     }

    for star in json_array:

        name = star['name']
        link = star['link']

        #!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!
        response = requests.get(link, headers=headers)

        bs = BeautifulSoup(response.text, 'html')

        pic_list_url = bs.select('.summary-pic a')[0].get('href')
        pic_list_url = 'https://baike.baidu.com' + pic_list_url

        pic_list_response = requests.get(pic_list_url, headers=headers)

        bs = BeautifulSoup(pic_list_response.text, 'lxml')
        pic_list_html = bs.select('.pic-list img ')

        pic_urls = []
        for pic_html in pic_list_html:
            pic_url = pic_html.get('src')
            pic_urls.append(pic_url)

        #!!!根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!!!
        down_pic(name,pic_urls)
def down_pic(name,pic_urls):
    '''
    根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
    '''
    path = 'work/'+'pics/'+name+'/'

    if not os.path.exists(path):
      os.makedirs(path)

    for i, pic_url in enumerate(pic_urls):
        try:
            pic = requests.get(pic_url, timeout=15)
            string = str(i + 1) + '.jpg'
            with open(path+string, 'wb') as f:
                f.write(pic.content)
                print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
        except Exception as e:
            print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
            print(e)
            continue

#四、打印爬取的所有图片的路径
def show_pic_path(path):
    '''
    遍历所爬取的每张图片,并打印所有图片的绝对路径
    '''
    pic_num = 0
    for (dirpath,dirnames,filenames) in os.walk(path):
        for filename in filenames:
           pic_num += 1
           print("第%d张照片:%s" % (pic_num,os.path.join(dirpath,filename)))           
    print("共爬取《青春有你2》选手的%d照片" % pic_num)
    if __name__ == '__main__':

     #爬取百度百科中《青春有你2》中参赛选手信息,返回html
     html = crawl_wiki_data()

     #解析html,得到选手信息,保存为json文件
     parse_wiki_data(html)

     #从每个选手的百度百科页面上爬取图片,并保存
     crawl_pic_urls()

     #打印所爬取的选手图片路径
     show_pic_path('/home/aistudio/work/pics/')

     print("所有信息爬取完成!")

未完待续。。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChangMQ267

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值