起源:hang
segmentfault.com/a/1190000010473819
简介
刚打仗python未几,做一个小名目来练练脚。前几天看了《战狼2》,发明它在最新上映的电影里面是排行第一的,如下图所示。筹备把豆瓣上对它的影评做一个剖析。
目的总览
重要做了三件事:
抓取网页数据
清算数据
用词云进行展现
使用的python版本是3.5.
1、抓取网页数据
第一步要对网页进行拜访,python中使用的是urllib库。代码如下:
from urllib import request
resp = request.urlopen("")
htmldata = resp.read().decode("utf-8")
此中
htmldata是字符串类型的变度,里面存放了网页的html代码。
输进print(htmldata)可以查看,如下图所示:
第发布步,需要对付获得的html代码进行剖析,失掉里里提取我们需要的数据。
在python中使用BeautifulSoup库进行html代码的解析。
(注:如果没有安装此库,则使用pip install BeautifulSoup进行安装即可!)
BeautifulSoup使用的格局如下:
BeautifulSoup(html,"html.parser")
第一个参数为需要提取数据的html,第二个参数是指定解析器,然后使用findall()读取html标签中的式样。
然而html中有那么多的标签,应读取哪些标签呢?实在,最简略的措施是我们能够挨开咱们爬取网页的html代码,而后查看我们须要的数据在哪个html标签外面,再进行读取便可能了。如下图所示:
从上图中可以看出在div id=”nowplaying“标签动手动手是我们想要的数据,里面有电影的名称、评分、主演等疑息。所以响应的代码编写如下:
from bs4 import BeautifulSoup as bs
soup = bs(htmldata, "html.parser")
nowplayingmovie = soup.findall("div", id="nowplaying")
nowplayingmovielist = nowplayingmovie[0].findall("li", class="list-item")
其中nowplayingmovielist 是一个列表,可以用print(nowplayingmovielist[0])查看里面的内容,如下图所示:
在上图中可以看到data-subject属性里面放了电影的id号码,而在img标签的alt属性里面放了电影的名字,因此我们就经由过程这两个属性来获得电影的id和名称。(注:打开电影短评的网页时需要用到电影的id,所以需要对它进行解析),编写代码如下:
nowplayinglist = []
for item in nowplayingmovielist:
nowplayingdict = {}
nowplayingdict["id"] = item["data-subject"]
for tagimgitem in item.findall("img"):
nowplayingdict["name"] = tagimgitem["alt"]
nowplayinglist.append(nowplayingdict)
个中列表nowplayinglist中就寄存了最新片子的id跟称号,可以使用print(nowplayinglist)进行查看,如下图所示:
可以看到和豆瓣网址下面是婚配的。如许就得到了最新电影的信息了。接下来就要进行对最新电影短评进行分析了。比方《战狼2》的短评网址为:
个中26363254就是电影的id,start=0流露表示评论的第0条评论。
接下来接对该网址进行解析了。打开上图中的短评页面的html代码,我们发现对于评论的数据是在div标签的comment属性下面,如下图所示:
因而对此标签进行解析,代码如下:
requrl = "" + nowplayinglist[0]["id"] + "/comments" +"?" +"start=0" + "&limit=20"
resp = request.urlopen(requrl)
htmldata = resp.read().decode("utf-8")
soup = bs(htmldata, "html.parser")
commentdivlits = soup.findall("div", class="comment")
此时在commentdivlits 列表中存放的就是div标签和comment属性下面的html代码了。在上图中借可以收现在p标签上面存放了网友对电影的批评,如下图所示:
因此对commentdivlits 代码中的html代码继绝进行解析,代码如下:
eachCommentList = [];
for item in commentdivlits:
if item.findall("p")[0].string is not None:
eachCommentList.append(item.findall("p")[0].string)
使用print(eachCommentList)查看eachCommentList列表中的内容,可以看到里面存里我们念要的影评。如下图所示:
好的,至此我们已经爬取了豆瓣比来播放电影的评论数据,接下来就要对数据进行清洗和词云显示了。
2、数据荡涤
为了便利进行数据进行浑洗,我们将列表中的数据放在一个字符串数组中,代码如下:
comments = ""
for k in range(len(eachCommentList)):
comments = comments + (str(eachCommentList[k])).strip()
使用print(comments)进行查看,如下图所示:
可以看到贪图的评论已酿成一个字符串了,当心是我们发现评论中另有很多的标面标记等。这些符号对我们进行词频统计时基本不用,果此要将它们肃清。所用的办法是正则表白式。python中正则抒发式是经过进程re模块来完成的。代码如下:
import re
pattern = re.compile(r"[一-�]+")
filterdata = re.findall(pattern, comments)
cleanedcomments = "".join(filterdata)
继承使用print(cleanedcomments)语句进行查看,如下图所示:
我们可以看到此时评论数据中已经没有那些标点符号了,数据变得“清洁”了良多。
因此要进行词频统计,以是前要进行中文分词草拟。在这里我使用的是结巴分词。假如出有装置结巴分词,可以在把持台使用pip install jieba进行安拆。(注:可使用pip list查看是否是安装了这些库)。代码如下所示:
import jieba #分词包
import pandas as pd
segment = jieba.lcut(cleanedcomments)
wordsdf=pd.DataFrame({"segment":segment})
由于结巴分词要用到pandas,所以我们这里减载了pandas包。可使用wordsdf.head()查看分词以后的结果,如下图所示:
从上图可以看到我们的数据中有“看”、“太”、“的”等实词(停用词),而这些词在职何情形中皆是下频时,而且没有现实的含意,所以我们要他们进行扫除。
我把停用词放在一个stopwords.txt文件中,将我们的数据取停用词进行比对即可(注:只有在百量中输出stopwords.txt,就可以下载到该文件)。往停用词代码如下代码如下:
stopwords=pd.readcsv("stopwords.txt",indexcol=False,quoting=3,欣欣图库看图印刷,sep="",names=["stopword"], encoding="utf-8")#quoting=3齐没有援用
wordsdf=wordsdf[~wordsdf.segment.isin(stopwords.stopword)]
持续应用wordsdf.head()语句去检查成果,以下图所示,停用伺候曾经被进来了。
接上去就要进行词频统计了,代码如下:
import numpy #numpy较劲争辩包
wordsstat=wordsdf.groupby(by=["segment"])["segment"].agg({"计数":numpy.size})
wordsstat=wordsstat.resetindex().sortvalues(by=["计数"],ascending=False)
用wordsstat.head()禁止查看,结果如下:
因为我们后面只是爬取了第一页的评论,所以数占有点少,在最后给出的完整代码中,我爬取了10页的评论,所数据还是有参考驾驶。
3、用词云进止显著
代码如下:
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
matplotlib.rcParams["figure.figsize"] = (10.0, 5.0)
from wordcloud import WordCloud#词云包
wordcloud=WordCloud(fontpath="simhei.ttf",backgroundcolor="white",maxfontsize=80)#指定字体类别、字体巨细和字体色彩
wordfrequence = {x[0]:x[1] for x in wordsstat.head(1000).values}
wordfrequencelist = []
for key in wordfrequence:
temp = (key,wordfrequence[key])
wordfrequencelist.append(temp)
wordcloud=wordcloud.fitwords(wordfrequencelist)
plt.imshow(wordcloud)
其中simhei.ttf使用来指定字体的,可以在百度上输入simhei.ttf进行下载后,放入法式的根目次即可。显示的图象如下:
到此为行,全部项目标先容就停止了。因为本人也仍是个入门者,接触python不暂,代码写的其实欠好。并且第一次写技巧专宾,表达的有些冗余,请各人多多原谅,有不对的处所,请大师批驳斧正。当前我也会将自己做的小项目以这类情势写在博客上和人人一路交换!最后揭上完全的代码。
完整代码
#coding:utf-8
author = "hang"
import warnings
warnings.filterwarnings("ignore")
import jieba #分词包
import numpy #numpy比赛争论包
import codecs #codecs供给的open方式来指定翻开的文明的说话编码,它会正在读与的时辰主动转换为外部unicode
import re
import pandas as pd
import matplotlib.pyplot as plt
from urllib import request
from bs4 import BeautifulSoup as bs
%matplotlib inline
import matplotlib
matplotlib.rcParams["figure.figsize"] = (10.0, 5.0)
from wordcloud import WordCloud#词云包
#分析网页函数
def getNowPlayingMovielist():
resp = request.urlopen("")
htmldata = resp.read().decode("utf-8")
soup = bs(htmldata, "html.parser")
nowplayingmovie = soup.findall("div", id="nowplaying")
nowplayingmovielist = nowplayingmovie[0].findall("li", class="list-item")
nowplayinglist = []
for item in nowplayingmovielist:
nowplayingdict = {}
nowplayingdict["id"] = item["data-subject"]
for tagimgitem in item.findall("img"):
nowplayingdict["name"] = tagimgitem["alt"]
nowplayinglist.append(nowplayingdict)
return nowplayinglist
#爬取评论函数
def getCommentsById(movieId, pageNum):
eachCommentList = [];
if pageNum>0:
start = (pageNum-1) * 20
else:
return False
requrl = "" + movieId + "/comments" +"?" +"start=" + str(start) + "&limit=20"
print(requrl)
resp = request.urlopen(requrl)
htmldata = resp.read().decode("utf-8")
soup = bs(htmldata, "html.parser")
commentdivlits = soup.findall("div", class="comment")
for item in commentdivlits:
if item.findall("p")[0].string is not None:
eachCommentList.append(item.findall("p")[0].string)
return eachCommentList
def main():
#轮回获得第一个电影的前10页评论
commentList = []
NowPlayingMovielist = getNowPlayingMovielist()
for i in range(10):
num = i + 1
commentListtemp = getCommentsById(NowPlayingMovielist[0]["id"], num)
commentList.append(commentListtemp)
#将列表中的数据转换为字符串
comments = ""
for k in range(len(commentList)):
comments = comments + (str(commentList[k])).strip()
#使用正则表达式去除标点符号
pattern = re.compile(r"[一-�]+")
filterdata = re.findall(pattern, comments)
cleanedcomments = "".join(filterdata)
#使用结巴分词进行中文分词
segment = jieba.lcut(cleanedcomments)
wordsdf=pd.DataFrame({"segment":segment})
#来失落停用词
stopwords=pd.readcsv("stopwords.txt",indexcol=False,quoting=3,sep="",names=["stopword"], encoding="utf-8")#quoting=3全不引用
wordsdf=wordsdf[~wordsdf.segment.isin(stopwords.stopword)]
#统计词频
wordsstat=wordsdf.groupby(by=["segment"])["segment"].agg({"计数":numpy.size})
wordsstat=wordsstat.resetindex().sortvalues(by=["计数"],ascending=False)
#用词云进行显示
wordcloud=WordCloud(fontpath="simhei.ttf",backgroundcolor="white",maxfontsize=80)
wordfrequence = {x[0]:x[1] for x in wordsstat.head(1000).values}
wordfrequencelist = []
for key in wordfrequence:
temp = (key,wordfrequence[key])
wordfrequencelist.append(temp)
wordcloud=wordcloud.fitwords(wordfrequencelist)
plt.imshow(wordcloud)
#主函数
main()
结果隐示如下:
上图基础反应了《战狼2》这部电影的情形。
――――开班喜信――――
温馨提示:马哥教导Python自动化开辟班将于8月28日在北京海淀上天开班,小班造莫非式讲课,钜惠限时夺位中。
马哥教育2017年Python自动化运维开发真战班,马哥结合BAT、豆瓣等一线互联网Python开发动人,依据今朝企业需要的Python开发人才进行了深度定制,参加了大批一线互联网公司:民众点评、饥了么、腾讯等出产情况实是项目,课程由浅入深,从Python根蒂基础到Python高等,让您融汇贯穿Python基础实践,手把手教学让你具有Python自动化开发需要的前端界面开发、Web框架、年夜监控体系、CMDB系统、认证碉堡机、自动化历程仄台六年夜实战才能,让你从0进部属手演变成Hold住年薪20万的Python自动化开辟人才。
课程咨询请少按便可征询