人工智能老师教AI,AI审核人工智能领域 横批:百度飞桨

Roselani ·
更新时间:2024-05-16
· 700 次阅读

       不觉”百度7日打卡Python+AI“学习已经过去5天,也该发点心得 了,收获颇丰啊

中间也踏过了很多小坑坑。分享一下了。

我的学习来源于百度AI aistudio。

https://aistudio.baidu.com/bdcpu6/user/281958/436937/notebooks/436937.ipynb?redirects=1

第五天的作业要求如下: 综合大作业

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

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

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

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

第三步:绘制词云

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

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

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

#!wget https://mydueros.cdn.bcebos.com/font/simhei.ttf # 下载中文字体 

 1 坑

如果下载不下来,可以去第2天作业中下载该字体

!cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/

# #创建字体目录fonts

#!mkdir .fonts

# # 复制字体文件到该路径

!cp simhei.ttf .fonts/

以上字体拷贝也要做,否则如下图

 3、模型安装

#安装模型

#!hub install porn_detection_lstm==1.1.0

#!pip install --upgrade paddlehub

不安装,内容分析时会报错。

#!pip install wordcloud  #云词库安装 不安装云词库运行时报错

4、准备爬评论

2坑

 &callback=jsonp_15xxxxxxxxxxxxxxxxxxx这个要去掉,否则返回的数据不是标准json,分析时出错。

5、可以正确完成作业的代码展示 5.1 引入所需要库

#请求爱奇艺评论接口,返回response信息 def getMovieinfo(url): ''' 请求爱奇艺评论接口,返回response信息 参数 url: 评论的url :return: response信息 ''' session=requests.Session() 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', 'Accept':'Application/json', } #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&last_id=240883095621&page=&page_size=20&types=time&callback=jsonp_1587991085438_40156' try: #response = requests.get(url,headers=headers) response=session.get(url,headers=headers) #print(response.status_code) if response.status_code==200: return response.text except Exception as e: print(e) return None return None #解析json数据,获取评论 def saveMovieInfoToFile(lastId,txtlst): ''' 解析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&last_id=' url=url+str(lastId) responseTxt=getMovieinfo(url) #pdb.set_trace() responseJson=json.loads(responseTxt) comments=responseJson['data']['comments'] for var in comments: if 'content' in var.keys(): #print(var['content']) txtlst.append(var['content']) lastId=str(var['id']) return str(lastId) #去除文本中特殊字符 def clear_special_char(content): ''' 正则处理特殊字符 参数 content:原文本 return: 清除后的文本 ''' #正则表达式过滤非中英文和数字的字符串 s=re.sub(r'| |\t\r',"",content) s=re.sub('[^\u4e00-\u9fa5^a-z^A-Z^0-9]', '', content) s=re.sub(r'\n',' ',s) s=re.sub(r'\*','\\*',s) s=re.sub('a-zA-Z','',s) #s=re.sub('^\d+(\.\d+)?$','',s) s = re.sub('^\d+(\.\d+)?$', '', 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) # 去除不可见字符 noqa return s def fenci(text): ''' 利用jieba进行分词 参数 text:需要分词的句子或文本 return:分词结果 ''' jieba.load_userdict('self_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').readline()] 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_aixs=[] y_axis=[] c_order=sorted(counts.items(),key=lambda x:x[1],reverse=True) for c in c_order[:num]: x_aixs.append(c[0]) y_axis.append(c[1]) #设置中文显示 #matplotlib.rcParams['font.sans-serif']=['SimHei'] #默认字体 #matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为SimHei显示中文 plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为SimHei显示中文 plt.rcParams['axes.unicode_minus']=False # 解决图像是负号‘-’显示为方块的问题 plt.figure(figsize=(20, 15)) plt.bar( range(len(y_axis)), y_axis,color='r', tick_label=x_aixs, facecolor='#9999ff', edgecolor='white' ) # 这里是调节横坐标的倾斜度,rotation是度数,以及设置刻度字体大小 plt.xticks(rotation=45, fontsize=20) plt.yticks(fontsize=20) plt.legend() #plt.bar(x_aixs,y_axis) plt.title('词频统计结果表') plt.savefig('high_words_pic.jpg') plt.show() #return None def drawcloud(word_f): ''' 根据词频绘制词云图 参数 word_f:统计出的词频结果 return:none ''' # 加载背景图片 cloud_mask = np.array(Image.open('/home/aistudio/cloudBg.png')) # 忽略显示的词 st = {'不是', '还是', '什么', '那么', '怎么', '就是', '没有'} font = r'/home/aistudio/.fonts/simhei.ttf' #pdb.set_trace(); # 生成wordcloud对象 wc = WordCloud( font_path=font, background_color='white', margin=5, mask=cloud_mask, max_words=200, min_font_size=10, max_font_size=100, width=800, height=600, relative_scaling=0.3, random_state=20, stopwords=st ) wc.fit_words(word_f) # 这种方式也可以 #wc.generate_from_frequencies(word_f) # 显示生成的词云 plt.imshow(wc) plt.axis("off") plt.show() wc.to_file('pic.png') def text_detection(text,file_path): ''' 使用hub对评论进行内容分析 text:返回列表 file_path:评论文件路径 return:分析结果 ''' porn_detection_lstm=hub.Module('porn_detection_lstm') with open(file_path,'r',encoding='utf-8') as f: for Line in f: if len(Line.strip())==1: continue else: text.append(Line) f.close() input_dict={"text":text} result=porn_detection_lstm.detection(data=input_dict,use_gpu=False,batch_size=1) #print(result) for index,item in enumerate(result): if item['porn_detection_key']=='porn': print(item['text'],item['porn_probs']) return result #评论是多分页的,得多次请求爱奇艺的评论接口才能获取多页评论,有些评论含有表情、特殊字符之类的 #num 是页数,一页10条评论,假如爬取1000条评论,设置num=100 主程序 if __name__ == "__main__": txlst=[] #评论内容列表 num=111 lastId='0' # 接口最后一个人员id with open('aqytl.txt','a',encoding='utf-8') as f: #追加方式打开文件 for i in range(num): saveMovieInfoToFile(lastId,txlst) time.sleep(0.5) #sleep 0.5s for item in txlst: item=clear_special_char(item) if item.strip()!='': try: f.write(item+'\n') except Exception as e: print('评论内容有特殊字符未清理') print('共爬取评论:'+str(len(txlst))) with open('aqytl.txt','r',encoding='utf-8') as fn: counts={} for Line in fn: words=fenci(Line) stopwords=stopwordslist('cn_stopwords.txt') movestopwords(words,stopwords,counts) drawcounts(counts,10) #top 10 高频词 drawcloud(counts) fn.close() ''' user hub 内容分析 ''' file_path='aqytl.txt' test_text=[] text_detection(test_text,file_path) display(Image.open('high_words_pic.jpg')) #显示生成的高频柱状图像 display(Image.open('pic.png')) #显示生成的词云图像 6 最后的输出结果 

6.1 柱状图  6.2 云词图 

总结: 

匆匆忙忙,学了很多,但还不牢固,需要再多练习,才能由Python小白升级。欢迎大家交流学习。

本次学习所得主要来自百度AI学习,谢谢各位老师及班班,还有同学的帮助!

https://aistudio.baidu.com/

starfoot 原创文章 1获赞 0访问量 50 关注 私信 展开阅读全文
作者:starfoot



领域 人工智能

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章