PaddlePaddle--python小白逆襲打卡營7日心得

在此之前已經參加過兩期打卡營了,第二期CV特輯的適合深感自己半路出家基礎太不牢靠了,PaddlePaddle是我第二個使用的深度學習框架,以前看過一些pytorch。之前兩期主要使用paddlepaddle搭建網絡,沒有詳細瞭解深度學習使用時就特別難,這期的paddlehub不一樣,簡單易用,搭建快速,只要懂python基礎,看着官方文檔,馬上就可以搞出來一個高大上的人工智能來。
參與前有些擔心因爲自己基本功不紮實,怕自己跟不上。但是參與之後發現,老師助教班班真的太棒了

day01

學習的是python基礎,簡單的循環和文件操作。比較難的一點就是文件操作(現在回頭再看,也不是那麼難),因爲當時不知道有 os.walk()這個方法只能“苦兮兮”的自己寫。

# 遞歸版本
def findfiles(path):
    #在這裏寫下您的查找文件代碼吧!
    directory = os.listdir(path)
    for one in directory:
        f = os.path.join(path,one)
        if os.path.isdir(f):   #遞歸搜索文件夾
            findfiles(f)
        elif os.path.isfile(f):
            if re.search(filename,f):
                result.append(f)
                print('[%d,\'%s\']'%(len(result),f))

#非遞歸版本
def findf():
    dire = os.listdir(path)
    paths = []
    for d in dire:
        paths.append(os.path.join(path,d))
    
    for p in paths:
        if os.path.isdir(p):
            dire = os.listdir(p)
            for d in dire:
                paths.append(os.path.join(p,d))
        elif os.path.isfile(p):
             if re.search(filename,p):
                result.append(p)
    
    for i in range(len(result)):
         print('[%d,\'%s\']'%(i+1,result[i]))

不過這些都不是重點,day01的重點是 百度AI技術體驗傳送門,體驗這個,對AI的興趣大增,也瞭解到了當前商業化應用AI的典型樣例(PS:動漫頭像製作好評~~~)

day02

學習的爬蟲,以前簡單瞭解過,但是沒用過bs4。這次使用bs4簡直就是如有神助,比正則舒服多了。

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

#獲取當天的日期,並進行格式化,用於後面文件命名,格式:20200420
today = datetime.date.today().strftime('%Y%m%d')    

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)

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)
    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中!!!
        pic_urls = []
        link2pic = getpichtml(link)
        pic_urls = getpicurl(link2pic)
        #!!!根據圖片鏈接列表pic_urls, 下載所有圖片,保存在以name命名的文件夾中!!!
        down_pic(name,pic_urls)

def getpichtml(url):
    '''
    獲取選手的百度相冊地址
    '''
    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'
    }                       
    try:
        response = requests.get(url,headers=headers)
        #將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
        soup = BeautifulSoup(response.text,'lxml')
        #找到相冊的連接地址並返回
        link2 = soup.find('a',{'nslog-type':'10002401'}).get("href")    
    except Exception as e:
        print(e)
    return 'https://baike.baidu.com'+link2

def getpicurl(url):
    '''
    獲取選手相冊的每一張圖片的地址
    '''
    result = []
    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'
    }                       
    try:
        response = requests.get(url,headers=headers)
        #將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
        soup = BeautifulSoup(response.text,'lxml')
        #找到相冊的連接地址並返回
        link = soup.find_all('a',{'class':'pic-item'})
        for item in link:
            #print(item.find("img")['src'])
            result.append(item.find("img")['src'])
         
    except Exception as e:
        print(e)
    return result
    
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

day03

學習的是數據可視化,使用plt來繪製圖片,這個還可以,唯一遺憾的地方是沒有使用pychart,圖片有點點醜。。。

plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體

plt.figure(figsize=(10,8))

plt.pie(x=x,labels=labels,explode=(0,0.1,0.1,0.2),autopct='%1.1f%%',shadow=True,startangle=0,textprops={'fontsize':15,'color':'black'})

plt.axis('equal')
plt.legend()
plt.title('''《青春有你2》參賽選手體重分佈''',fontsize = 24)

在這裏插入圖片描述
使用中文是個大坑這個下載地址好像出問題了,大家可以自己去其它地方下一個,然後上傳到aistudio即可

#aistudio平臺代碼如下
# 下載中文字體
!wget https://mydueros.cdn.bcebos.com/font/simhei.ttf
# 將字體文件複製到matplotlib字體路徑
!cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/
# 一般只需要將字體文件複製到系統字體目錄下即可,但是在aistudio上該路徑沒有寫權限,所以此方法不能用
# !cp simhei.ttf /usr/share/fonts/

# 創建系統字體文件路徑
!mkdir .fonts
# 複製文件到該路徑
!cp simhei.ttf .fonts/
!rm -rf .cache/matplotlib

day04

學習圖片分類,要求分五類,但是圖片不好找呀,尤其是anqi的,數據集就搞了好久。

這時百度百科爬的圖片


import re
import requests
from bs4 import BeautifulSoup
import os

def getpichtml(url):
    link = []
    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'
    }                       
    try:
        response = requests.get(url,headers=headers)
        #將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
        soup = BeautifulSoup(response.text,'html.parser')
        #找到相冊的連接地址並返回
        link.append('https://baike.baidu.com'+soup.find('a',{'nslog-type':'10002401'}).get("href"))
        for link2 in soup.find_all('a',{'class':'lemma-album layout-right nslog:10000206'}):
            link.append('https://baike.baidu.com'+link2.get("href"))
    except Exception as e:
        print(e)
    return link



def getpicurl(url):
    '''
    獲取選手相冊的每一張圖片的地址
    '''
    result = []
    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'
    }                       
    try:
        response = requests.get(url,headers=headers)
        #將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
        soup = BeautifulSoup(response.text,'html.parser')
        link = soup.find_all('a',{'class':'pic-item'})
        for item in link:
            #print(item.find("img")['src'])
            result.append(item.find("img")['src'])
         
    except Exception as e:
        print(e)
    return result


def down_pic(name,pic_urls):
    '''
    根據圖片鏈接列表pic_urls, 下載所有圖片,保存在以name命名的文件夾中,
    '''
    path = 'dataset/'+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

urls = [
    'https://baike.baidu.com/item/%E8%99%9E%E4%B9%A6%E6%AC%A3/2977841', #yushuxin
    'https://baike.baidu.com/item/%E8%AE%B8%E4%BD%B3%E7%90%AA/4970805', #xujiaqi
    'https://baike.baidu.com/item/%E8%B5%B5%E5%B0%8F%E6%A3%A0/24274480', #zhaoxiaotang
    'https://baike.baidu.com/item/%E5%AE%89%E5%B4%8E/22831154',          #anqi
    'https://baike.baidu.com/item/%E7%8E%8B%E6%89%BF%E6%B8%B2/24275812'  #wangchengxuan
]
file_name=['yushuxin','xujiaqi','zhaoxiaotang','anqi','wangchengxuan']
iii=0
for url in urls:
    links = []
    links = getpichtml(url)
    pic_url = []
    for lin in links:
        pic_url.extend(getpicurl(lin))
    down_pic(file_name[iii],pic_url)
    iii = iii+1

圖片一定一定要自己清洗一下,不然後面報錯報個沒完

# from PIL import Image

# urls = os.listdir('./dataset/anqi/')

# for url in urls:
#     tmp = './dataset/anqi/'+url
#     try:
#         Image.open(tmp).load()
#     except OSError:
#         os.remove(tmp)
#         print(tmp)

配置paddlehub來訓練,這個東東簡化了好多好多好多步驟,一個訓練可能10來行就完事了,用了這個完全不想用pytorch了

import paddlehub as hub
module = hub.Module(name="resnet_v2_50_imagenet")
from paddlehub.dataset.base_cv_dataset import BaseCVDataset
   
class DemoDataset(BaseCVDataset):	
   def __init__(self):	
       # 數據集存放位置
       
       self.dataset_dir = "/home/aistudio/dataset"  #這個是文件夾地址,裏面有train_list.txt這些
       super(DemoDataset, self).__init__(
           base_path=self.dataset_dir,
           train_list_file="train_list.txt",
           validate_list_file="validate_list.txt",
           test_list_file="test_list.txt",
           label_list_file="label_list.txt",
           )
dataset = DemoDataset()

#生成數據集這個是
import os

with open('./dataset/train_list.txt','w') as f:
    for root, dirs, files in os.walk("./dataset/yushuxin", topdown=False):
        for ind in files:
            s = 'yushuxin/'+ind+' 0\n'
            f.write(s)
    for root, dirs, files in os.walk("./dataset/xujiaqi", topdown=False):
        for ind in files:
            s = 'xujiaqi/'+ind+' 1\n'
            f.write(s)
    for root, dirs, files in os.walk("./dataset/zhaoxiaotang", topdown=False):
        for ind in files:
            s = 'zhaoxiaotang/'+ind+' 2\n'
            f.write(s)
    for root, dirs, files in os.walk("./dataset/anqi", topdown=False):
        for ind in files:
            s = 'anqi/'+ind+' 3\n'
            f.write(s)
    for root, dirs, files in os.walk("./dataset/wangchengxuan", topdown=False):
        for ind in files:
            s = 'wangchengxuan/'+ind+' 4\n'
            f.write(s)

data_reader = hub.reader.ImageClassificationReader(
    image_width=module.get_expected_image_width(),
    image_height=module.get_expected_image_height(),
    images_mean=module.get_pretrained_images_mean(),
    images_std=module.get_pretrained_images_std(),
    dataset=dataset)

配置策略
在進行Finetune前,我們可以設置一些運行時的配置,例如如下代碼中的配置,表示:

use_cuda:設置爲False表示使用CPU進行訓練。如果您本機支持GPU,且安裝的是GPU版本的PaddlePaddle,我們建議您將這個選項設置爲True;

epoch:迭代輪數;

batch_size:每次訓練的時候,給模型輸入的每批數據大小爲32,模型訓練時能夠並行處理批數據,因此batch_size越大,訓練的效率越高,但是同時帶來了內存的負荷,過大的batch_size可能導致內存不足而無法訓練,因此選擇一個合適的batch_size是很重要的一步;

log_interval:每隔10 step打印一次訓練日誌;

eval_interval:每隔50 step在驗證集上進行一次性能評估;

checkpoint_dir:將訓練的參數和數據保存到cv_finetune_turtorial_demo目錄中;

strategy:使用DefaultFinetuneStrategy策略進行finetune;

更多運行配置,請查看RunConfig

同時PaddleHub提供了許多優化策略,如AdamWeightDecayStrategy、ULMFiTStrategy、DefaultFinetuneStrategy等,詳細信息參見策略

config = hub.RunConfig(
    use_cuda=True,                              #是否使用GPU訓練,默認爲False;
    num_epoch=10,                                #Fine-tune的輪數;
    checkpoint_dir="cv_finetune_turtorial_demo",#模型checkpoint保存路徑, 若用戶沒有指定,程序會自動生成;
    batch_size=8,                              #訓練的批大小,如果使用GPU,請根據實際情況調整batch_size;
    eval_interval=20,                           #模型評估的間隔,默認每100個step評估一次驗證集;
    strategy=hub.finetune.strategy.L2SPFinetuneStrategy(learning_rate=1e-4,optimizer_name="adam",regularization_coeff=1e-3))  #Fine-tune優化策略;

組建Finetune Task
有了合適的預訓練模型和準備要遷移的數據集後,我們開始組建一個Task。

由於該數據設置是一個二分類的任務,而我們下載的分類module是在ImageNet數據集上訓練的千分類模型,所以我們需要對模型進行簡單的微調,把模型改造爲一個二分類模型:

獲取module的上下文環境,包括輸入和輸出的變量,以及Paddle Program; 從輸出變量中找到特徵圖提取層feature_map;
在feature_map後面接入一個全連接層,生成Task;

input_dict, output_dict, program = module.context(trainable=True)
img = input_dict["image"]
feature_map = output_dict["feature_map"]
feed_list = [img.name]

task = hub.ImageClassifierTask(
    data_reader=data_reader,
    feed_list=feed_list,
    feature=feature_map,
    num_classes=dataset.num_labels,
    config=config)

開始Finetune
我們選擇finetune_and_eval接口來進行模型訓練,這個接口在finetune的過程中,會週期性的進行模型效果的評估,以便我們瞭解整個訓練過程的性能變化。

run_states = task.finetune_and_eval()

訓練完以後的預測結果

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg

with open("./dataset/test_list.txt","r") as f:
    filepath = f.readlines()

#data = [filepath[0].split(" ")[0],filepath[1].split(" ")[0],filepath[2].split(" ")[0],filepath[3].split(" ")[0],filepath[4].split(" ")[0]]
data = ['dataset/'+filepath[0].split(" ")[0],'dataset/'+filepath[1].split(" ")[0],'dataset/'+filepath[2].split(" ")[0],'dataset/'+filepath[3].split(" ")[0],'dataset/'+filepath[4].split(" ")[0]]
label_map = dataset.label_dict()
index = 0
run_states = task.predict(data=data)
results = [run_state.run_results for run_state in run_states]

for batch_result in results:
    print(batch_result)
    batch_result = np.argmax(batch_result, axis=2)[0]
    print(batch_result)
    for result in batch_result:
        index += 1
        result = label_map[result]
        print("input %i is %s, and the predict result is %s" %
              (index, data[index - 1], result))

訓練完以後的預測結果

day05

大作業,聽着就叫人頭大,愛奇藝的評論爬取就爬了一天,還是晚上聽了小哥哥的講解才學會如何正確的爬取那些東東。
在這裏插入圖片描述
這種樣子的bs4已經沒用用武之地了,分析network,找他的評論
在這裏插入圖片描述
這時request的URL,多抓幾個你會發現,只有last_id不同,而且第一個的last_id後面不用寫,而這個last_id就是上面json文件中最後一個評論用戶的id,url裏面的page_size 也可改變,表示最大加載多少評論,最大可以改到40。
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=10&last_id=&page=&page_size=10&types=hot,time
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=0&last_id=241161657921&page=&page_size=20&types=time
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=0&last_id=241064309921&page=&page_size=20&types=time

瞭解到這裏,就可以歡快的開始爬取評論了

from __future__ import print_function
import requests
import json
import re #正則匹配
import time #時間處理模塊
import jieba #中文分詞
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
from PIL import Image
from wordcloud import WordCloud  #繪製詞雲模塊
import paddlehub as hub

#請求愛奇藝評論接口,返回response信息
def getMovieinfo(url):
    '''
    請求愛奇藝評論接口,返回response信息
    參數  url: 評論的url
    :return: response信息
    '''
    session = requests.Session()
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36",
        "Accept": "application/json",
        "Referer": "https://www.iqiyi.com/v_19ryfkiv8w.html",
        "Origin": "http://m.iqiyi.com",
        "Host": "sns-comment.iqiyi.com",
        "Connection": "keep-alive",
        "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6",
        "Accept-Encoding": "gzip, deflate,br"
    }
    response = session.get(url, headers=headers)
    if response.status_code == 200:
        return response.text
    return None


#解析json數據,獲取評論
def saveMovieInfoToFile(lastId,arr):
    '''
    解析json數據,獲取評論
    參數  lastId:最後一條評論ID  arr:存放文本的list
    :return: 新的lastId
    '''
    url = "https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15068699100&hot_size=0&page=&page_size=20&types=time&last_id="
    url += str(lastId)
    responseText = getMovieinfo(url)
    responseJson = json.loads(responseText)
    comments = responseJson['data']['comments']
    for val in comments:
        if 'content' in val.keys():
            print(val['content'])
            arr.append(val['content'])
        lastId = str(val['id'])
    return lastId

#去除文本中特殊字符
def clear_special_char(content):
    '''
    正則處理特殊字符
    參數 content:原文本
    return: 清除後的文本
    '''
    s = re.sub(r'</?(.+?)>|&nbsp;|\t|\r',"",content)
    s = re.sub(r'\n'," ",s)
    s = re.sub(r'\*',"\\*",s)
    s = re.sub('[^\u4e00-\u9fa5^a-z^A-Z^0-9]','',s)
    s = re.sub('[\001\002\003\004\005\006\007\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a]','',s)
    s = re.sub('[a-zA-Z]','',s)
    s = re.sub('^\d+(\.\d+)?$','',s)

    return s

add_words.txt就是一個人工添加的詞語,比如 奧裏給,衝鴨 這些jieba不懂的

def fenci(text):
    '''
    利用jieba進行分詞
    參數 text:需要分詞的句子或文本
    return:分詞結果
    '''
    jieba.load_userdict('add_words.txt')
    seg = jieba.lcut(text,cut_all=False)
    return seg

停詞表就是 可以,只是,因爲 這類的沒用實際意義的詞語

def stopwordslist(file_path):
    '''
    創建停用詞表
    參數 file_path:停用詞文本路徑
    return:停用詞list
    '''
    stopwords = [line.strip() for line in open(file_path,encoding='UTF-8').readlines()]
    
    return stopwords

def movestopwords(sentence,stopwords,counts):
    '''
    去除停用詞,統計詞頻
    參數 file_path:停用詞文本路徑 stopwords:停用詞list counts: 詞頻統計結果
    return:None
    '''
    out = []
    for word in sentence:
        if word not in stopwords:
            if len(word) != 1:
                counts[word] = counts.get(word,0) + 1
    return None

def drawcounts(counts,num):
    '''
    繪製詞頻統計表
    參數 counts: 詞頻統計結果 num:繪製topN
    return:none
    '''
    x_aixes = []
    y_aixes = []
    c_order = sorted(counts.items(),key=lambda x:x[1],reverse=True)

    for c in c_order[:num]:
        x_aixes.append(c[0])
        y_aixes.append(c[1])

    matplotlib.rcParams['font.sans-serif'] = ['simhei']
    matplotlib.rcParams['axes.unicode_minus'] = False  #解決圖片負號 - 保存顯示方塊問題
    plt.bar(x_aixes,y_aixes)
    plt.title("詞頻統計")
    plt.show()
    return None
def drawcloud(word_f):
    '''
    根據詞頻繪製詞雲圖
    參數 word_f:統計出的詞頻結果
    return:none
    '''
    #print(word_f)
    
    #加載背景圖片
    cloud_mask = np.array(Image.open("./4.jpg"))
    #忽略顯示的詞
    st=set(['可是'])
    #生成wordcloud對象
    wc = WordCloud(background_color="white", 
        mask=cloud_mask,
        max_words=300,
        font_path="STFANGSO.TTF",
        stopwords=st)
    # 加載詞頻字典
    wc.fit_words(word_f)
    
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()

    wc.to_file("pic.png")
def text_detection(text_text,file_path):
    '''
    使用hub對評論進行內容分析
    return:分析結果

    '''

    porn_detection_lstm = hub.Module(name='porn_detection_lstm')
    f = open('aqy.txt','r',encoding='utf-8')
    for line in f:
        if len(line.strip() ) == 1:
            continue
        else:
            text_text.append(line)
    f.close()
    input_dict = {"text":text_text}
    results = porn_detection_lstm.detection(data=input_dict,use_gpu=True,batch_size=1)
    for index,item in enumerate(results):
        if item['porn_detection_key'] == 'porn':
            print(item['text'],":",item['porn_probs'])
#評論是多分頁的,得多次請求愛奇藝的評論接口才能獲取多頁評論,有些評論含有表情、特殊字符之類的
#num 是頁數,一頁10條評論,假如爬取1000條評論,設置num=100
if __name__ == "__main__":
    num = 60
    lastId = '0'
    arr = []
    with open('aqy.txt','a',encoding='utf-8') as f:
        for i in range(num):
            lastId = saveMovieInfoToFile(lastId,arr)
            time.sleep(0.5)
        for item in arr:
            Item = clear_special_char(item)
            if Item.strip() !='':
                try:
                    f.write(Item+'\n')
                except Exception as e:
                    print('含有特殊字符')
    print('共獲取評論: ',len(arr))
    f = open('aqy.txt','r',encoding='utf-8')
    counts = {}
    for line in f:
        words = fenci(line)
        stopwords = stopwordslist('stopwords-cn.txt')
        movestopwords(words,stopwords,counts)
    
    drawcounts(counts,10)
    drawcloud(counts)
    f.close()

    file_path = 'aqy.txt'
    text_text = []
    text_detection(text_text,file_path)

經過這一期打卡營,python基礎有了很大的提高,以前不懂的一些東西,現在聽力講解有一種原來如此的感覺。

特別在這裏感謝每天晚上直播講解的文姐姐和小哥哥,還有最美的班班~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章