【飞浆paddlepaddle】python 您所在的位置:网站首页 青春有你选手图片 【飞浆paddlepaddle】python

【飞浆paddlepaddle】python

2024-07-12 00:52| 来源: 网络整理| 查看: 265

文章目录 1. 踩坑记1.1.字体乱码403FORBIDDEN 解决方法1:本地上传字体文件解决方法2:重新新建一个项目1.2.词云问题 2. 综合大作业:《青春有你2》选手数据分析以及评论分析2.1.实现步骤2.2.需要的配置和准备 3.结果展示3.1.爬取评论部分截图3.2.TOP-10词频柱状图3.3.词云展示(我吐了,还是没解决。词云仍然没形状) 4.LAST:这里获取词云所需背景图(抠图)4.1.效果展示 5.总结

1. 踩坑记

(补坑再遇坑,希望知道怎么让词云有形状的朋友们,大佬们可以指点指点当然,还有评分分析的时候,一直在运行,但是好久没有结果,懵了。)

1.1.字体乱码

1.命令下载中文字体文件,然后移动到 ".fonts/"文件夹中,正常来说,字体文件存在对于的文件夹中,应该生效才对。不过程序运行出来的柱状图的文字仍然是乱码。

2.本地上传中文字体文件,然后移动到 ".fonts/"文件夹中,仍然解决不了。

3.程序报错说:‘Font-family’ not found. 。于是我去修改字体的配置文件,并且重启环境,仍然不能解决。

最后,我是把整个环境重置为最初的版本,终于,在这里可以正常下载字体文件,不再是403forbidden了。之后,在动字体文件的时候,手动输入的字体文件名,如果该字体文件名有提示,则表示命令可以找到这个文件,所以经过这个过程,同时重启环境之后。终于正常显示中文字体了。

今天先写着最为深刻的一个坑,后续再补代码和坑。 (补坑再遇坑,希望知道怎么让词云有形状的朋友们,大佬们可以指点指点。)

403FORBIDDEN # 下载中文字体 !wget https://mydueros.cdn.bcebos.com/font/simhei.ttf --2020-05-03 22:14:32-- https://mydueros.cdn.bcebos.com/font/simhei.ttf Resolving mydueros.cdn.bcebos.com (mydueros.cdn.bcebos.com)... 182.61.200.229, 182.61.200.195 Connecting to mydueros.cdn.bcebos.com (mydueros.cdn.bcebos.com)|182.61.200.229|:443... connected. HTTP request sent, awaiting response... 403 Forbidden 2020-05-03 22:14:32 ERROR 403: Forbidden.

参考网络上的一般解决方法是:

!wget -O 'test.zip' URL !wget -U "你的User-Agent" URL

但是这些方法在paddle提供的环境好像不起作用。

解决方法1:本地上传字体文件

SimHei.ttf中文字体下载【点击这里】01 SimHei.ttf中文字体下载【点击这里】02 下载完成之后,在paddle环境中点击上传文件,选择simhei.ttf文件上传,然后复制文件到 .fonts文件夹中,重启服务,中文字体就可以正常显示了。

# 创建字体目录fonts !mkdir .fonts # 复制字体文件到该路径 !cp simhei.ttf .fonts/ """另外一种移动字体文件方法""" # 将字体文件复制到matplotlib字体路径 !cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/

移动字体文件后可能在系统中仍然找不到可用的中文字体:在这里插入图片描述

解决方法2:重新新建一个项目

这个时候wget是可以正常下载字体文件的,response code = 200 OK; 然后就可以正常执行,创建字体文件夹,复制字体文件到文件夹中。如果此时还是不能正常显示中文,则需要停止项目,然后再启动,就可以解决了。 在这里插入图片描述

1.2.词云问题

在这里插入图片描述

2. 综合大作业:《青春有你2》选手数据分析以及评论分析 2.1.实现步骤

第一步:爱奇艺《青春有你2》评论数据爬取(参考链接:https://www.iqiyi.com/v_19ryfkiv8w.html#curid=15068699100_9f9bab7e0d1e30c494622af777f4ba39)

爬取任意一期正片视频下评论评论条数不少于1000条

第二步:词频统计并可视化展示

数据预处理:清理清洗评论中特殊字符(如:@#¥%、emoji表情符),清洗后结果存储为txt文档中文分词:添加新增词(如:青你、奥利给、冲鸭),去除停用词(如:哦、因此、不然、也好、但是)统计top10高频词可视化展示高频词

第三步:绘制词云

根据词频生成词云可选项-添加背景图片,根据背景图片轮廓生成词云

第四步:结合PaddleHub,对评论进行内容审核

2.2.需要的配置和准备 中文分词需要jieba词云绘制需要wordcloud可视化展示中需要的中文字体网上公开资源中找一个中文停用词表根据分词结果自己制作新增词表准备一张词云背景图(附加项,不做要求,可用hub抠图实现)paddlehub配置

安装“jieba”+“worldcloud”库

# Linux系统默认字体文件路径 !ls /usr/share/fonts/ # 查看系统可用的ttf格式中文字体 !fc-list :lang=zh | grep ".ttf" [OUT]: cmap truetype type1 X11 /home/aistudio/.fonts/simhei.ttf.1: SimHei,黑体:style=Regular,Normal,obyčejné,Standard,Κανονικά,Normaali,Normál,Normale,Standaard,Normalny,Обычный,Normálne,Navadno,Arrunta # 安装模型 !hub install porn_detection_lstm==1.1.0 !pip install --upgrade paddlehub

在这里插入图片描述 1.导入所需的库

from __future__ import print_function import requests import json import six import re #正则匹配 import time #时间处理模块 import jieba #中文分词 import numpy as np import matplotlib import collections import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager from matplotlib.font_manager import FontProperties from PIL import Image from wordcloud import WordCloud #绘制词云模块 import paddlehub as hub

2.爬取爱奇艺《青春有你2》视频评论

#请求爱奇艺评论接口,返回response信息 def getMovieinfo(last_id): ''' 请求爱奇艺评论接口,返回response信息 参数 url: 评论的url :return: response信息| ''' if last_id=='': page_size=10 else: page_size=40 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='+str(page_size)+'&types=time&callback=jsonp&&last_id='+str(last_id) response = requests.get(url, timeout=10) # print(result.text) return response #解析json数据,获取评论 def saveMovieInfoToFile(text): ''' 解析json数据,获取评论 参数 lastId:最后一条评论ID arr:存放文本的list :return: 新的lastId ''' pattern = re.compile('.*?jsonp[(](.*?)[)] }catch', re.S) items = re.findall(pattern, text) if len(items)==0: return '' data_json=json.loads(items[0]) # print(data_json) comments=data_json['data']['comments'] f_comments=open('work/comments.txt','a') for comment in comments: if 'content' not in comment: continue f_comments.write(comment['content']+'\n') last_id=comment['id'] f_comments.close crawl_num=len(comments) # print(comments) return last_id,crawl_num

3.数据预处理——去除文本中特殊字符

# #去除文本中特殊字符 def clear_special_char(content): ''' 正则处理特殊字符 参数 content:原文本 return: 清除后的文本 ''' f_clear = open('work/clear_comments.txt','a') clear_content = re.findall('[\u4e00-\u9fa5a-zA-Z0-9]+',content,re.S) #只要字符串中的中文,字母,数字 word_str=','.join(clear_content) f_clear.write(word_str+'\n') f_clear.close return word_str

4.建立合适的分词库

def fenci(content): ''' 利用jieba进行分词 参数 text:需要分词的句子或文本 return:分词结果 ''' # 加载本地词库 jieba.load_userdict(r"add_words.txt") reviews = jieba.cut(content, cut_all=False) return reviews

5.创建停用词表

def stopwordslist(): ''' 创建停用词表 参数 file_path:停用词文本路径 return:停用词list ''' stopwords = [line.strip() for line in open('work/stopwords.txt',encoding='UTF-8').readlines()] # stopwords = [] acstopwords=['哦','因此','不然','也好','但是','一定','多么','多亏','哎呀','哎哟'] stopwords.extend(acstopwords) return stopwords

6.去除停用词

def movestopwords(words,stopwords,counts): ''' 去除停用词,统计词频 参数 file_path:停用词文本路径 stopwords:停用词list counts: 词频统计结果 return:None ''' # counts = {} for word in words: if word not in stopwords: if len(word) != 1: counts[word] = counts.get(word,0) + 1

7.绘制词频统计表

def drawcounts(counts,num): ''' 绘制词频统计表 参数 counts: 词频统计结果 num:绘制topN return:none ''' # 词频统计 x_values=[] y_values=[] z_list = sorted(counts.items(), key=lambda x:x[1], reverse=True) # print(z_list) for val in z_list[:num]: x_values.append(val[0]) y_values.append(val[1]) plt.rcParams['axes.unicode_minus']=False plt.rcParams['font.sans-serif'] = ['SimHei'] # 上述方式不生效时,可以尝试下面方法设置中文字体 # fname对应你的字体文件名,在需要显示中文的代码加上:, FontProperties=font font = FontProperties(fname=r"simhei.ttf.1", size=14) plt.figure(figsize=(15, 10)) plt.bar(x_values, y_values,color='r',facecolor='#9999ff',edgecolor='white') # 这里是调节横坐标的倾斜度,rotation是度数,以及设置刻度字体大小 plt.xticks(rotation=45,fontsize=16, fontproperties=font) plt.yticks(fontsize=16, fontproperties=font) plt.title('''《青春有你2》词频统计''',fontsize = 20, fontproperties=font) plt.savefig('highwords.jpg') plt.show()

8.绘制词云图

def drawcloud(word_f): ''' 根据词频绘制词云图 参数 word_f:统计出的词频结果 return:none ''' # 背景图片 # mask=np.array(Image.open(r'humanseg_output/sendimg.png')) mask=np.array(Image.open(r'humanseg_output/yushux.png')) # 忽略显示词 st = set(['东西', '这是', '就是', '怎么', '可能', '需要', '不行']) New_wordcloud = WordCloud( font_path='simhei.ttf.1', stopwords=st, mask=mask, background_color='white', max_words=250, relative_scaling=0.3, max_font_size=100, min_font_size=10, width=800, height=600, random_state=10, collocations=False, #避免重复单词 ).generate_from_frequencies(word_f) # New_wordcloud.fit_words(word_f) # 保存词云结果图 New_wordcloud.to_file('pic.png')

9.评论分析 (这里模型运行一直很久,还没解决)

最后,调用情况在这里:

#评论是多分页的,得多次请求爱奇艺的评论接口才能获取多页评论,有些评论含有表情、特殊字符之类的 #num 是页数,一页10条评论,假如爬取1000条评论,设置num=100 if __name__ == "__main__": # 爬取评论 response=getMovieinfo('') cur_last_id,total_crawl=saveMovieInfoToFile(response.text) num=0 while cur_last_id !='' : if num >30: break cur_last_id,total=saveMovieInfoToFile(getMovieinfo(cur_last_id).text) total_crawl+=total num+=1 print('总共爬取评论:%d条'%(total_crawl)) with open('work/comments.txt', encoding='utf-8') as f: pri_content = f.readlines() f.close() for i in pri_content: str_content = clear_special_char(i) # 预处理 seg_list = fenci(str_content) # 分词结果 # 创建停用词表 with open('work/comments.txt', encoding='utf-8') as f: counts = {} for ls in f: ls = ls.replace('\n','') # print(ls) reviews = fenci(ls) # 分词结果 stopwords = stopwordslist() # 得到停用词表 movestopwords(reviews,stopwords,counts) # 去除停用词,统计词频 # print(segments) drawcounts(counts,10) # 词频统计图 drawcloud(counts) # 词云图 text_detection() # 评论分析 display(Image.open('pic.png')) #显示生成的词云图像 3.结果展示 3.1.爬取评论部分截图

在这里插入图片描述

3.2.TOP-10词频柱状图

在这里插入图片描述

3.3.词云展示(我吐了,还是没解决。词云仍然没形状)

在这里插入图片描述

4.LAST:这里获取词云所需背景图(抠图) ## 抠图 import sys import os import paddlehub as hub # 加载模型 humanseg = hub.Module(name = "deeplabv3p_xception65_humanseg") # 抠图 results = humanseg.segmentation(data = {"image":['yushux.jpg']}) for result in results: print(result['origin']) print(result['processed']) 4.1.效果展示

在这里插入图片描述

5.总结

短短7天时间,在飞桨平台提供技术支持的百度python+AI打卡营中,涉及的知识面之广和知识量之大,不是我们平常所见所想的! 在第一天的python入门基础之后,迎来的是python的爬虫领域,在这里,对于小白来说,知识跨度有点大,可能大部分朋友还在苦恼第一天的任务,而第二天的任务缺接近截止尾声了!!!(那种真是每行代码都要去百度去查去群问的的时候,真是太难了!不得不说很容易就落下了~~) 对于第三天,有着承前启后的意义,针对爬取下来的选手信息进行数据分析以及可视化。不得不说,这种学完即用的,接收新知识的同时,联想前面学过的,这个安排的确不错。而且难度稍微降低,可以在大家小白入门之后有些时间可以“喘息”,进而留有时间总结过去三天的知识框架。 对于第四天,这是由python引进图像识别领域,基本目的是通俗理解图像处理。任务是对《青春有你2》TOP-N选手进行图像识别(paddlehub的库太强了)。 … 这些天以来,逐渐明白,学习,不要单单一个人闷着头学,要乐于交流,乐于分享,互帮互助,共同进步。希望百度的打卡营活动越来越好,让大众更加了解飞桨平台使用的便利性和技术的强大。也希望自己可以在这次活动之后养成写博客的习惯。 最后,感谢一直以来人美心善的班班和默默奉献的助教以及教授知识的文老师和其他可爱的老师们!还要感谢4群帮助过、指点过的我的朋友们!谢谢你们!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有