Python2.7 爬虫实践:豆瓣电影影评分析

reference from :hang

segmentfault.com/a/1190000010473819


本人先看到以上,觉得挺好玩,所以就跟着原作者的思路在撸一遍代码

后来发现了几个问题

本人的python 2.7 原作者为python3

所以其中的一些funtion/属性 也不支持

所以做了一下修改

安装必要的lib 之后会有文章进行介绍

好了 就先上代码吧


__author__ = 'Helen Huang'

# encoding=utf8
import sys
import warnings
warnings.filterwarnings("ignore")
reload(sys)
sys.setdefaultencoding('utf8')
from urllib2 import urlopen
import bs4
import time
import re
import jieba
import numpy
import codecs
import matplotlib.pyplot as plt
import matplotlib
from wordcloud import WordCloud
import pandas as pd


matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)

def getMovieId(title):
    resp = urlopen('https://movie.douban.com/nowplaying/hangzhou/')
    html_data = resp.read().decode('utf-8')
    soup = bs4.BeautifulSoup(html_data,"html.parser")
    content = soup.find_all('div',id='nowplaying')
    movieStrList=content[0].find_all('li',class_ ='list-item')
    movieList=[]
    for item in movieStrList:
        movie_dit={}
        movie_dit['id']=item['data-subject']
        movie_dit['name']=item['data-title']
        movieList.append(movie_dit)
        item['data-title']=item['data-title'].strip('')
        if unicode(item['data-title']) == (title):
            movieId =item['data-subject']
            if unicode(item['data-title']) == (title):
                return movieId

def getCommentsById(movieId,pageNum):

  #避免uncode出现在云图,所以我直接将结果保存为str
    for i in range(10):
        num = i + 1
        if pageNum >0 :
            start =(num-1) * 20
        else:
            return False
        reqUrl='https://movie.douban.com/subject/' + movieId + '/comments' +'?' +'start=' + str(start) + '&limit=20'
        print reqUrl
        resp = urlopen(reqUrl)
        html = resp.read().decode('utf-8')
        #print html
        soup = bs4.BeautifulSoup(html,"html.parser")
        comContent = soup.find_all('div',id='comments')
        #print comContent
        commentStr=comContent[0].find_all('div',class_ ='comment')
        commentList =[]
        comments=''
        for comment in commentStr:
            c = comment.find_all('p')[0].string
            if c is not None:
                commentList.append(c)
                comments =comments+str(c).strip().strip('\n')
                print c
        return comments
if __name__ == '__main__':
    print 'start ....'
    title=u'杀破狼·贪狼'
    movieId = getMovieId(title)
    print 'movie id is:'
    print movieId
    comments = getCommentsById(movieId,10)
    comments=comments.replace(' ','')
    print comments
    #使用正则表达式去除标点符号
    pattern = re.compile(r'[\u4e00-\u9fa5]+')
    filterdata = re.findall(pattern, comments)
    cleaned_comments = ''.join(filterdata)
    cleaned_comments= comments
    #使用结巴分词进行中文分词
    segment = jieba.lcut(cleaned_comments)
    words_df=pd.DataFrame({'segment':segment})

    #去掉停用词 #如果有电影领域的停用词就更好了
    #stopwords=pd.read_csv('D:\python\stopwords.txt',index_col=False,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用

    #python27 没有quoting 属性
    stopwords=pd.read_csv('D:\python\stopwords_copy.txt',names=['stopword'], encoding='utf-8')
    words_df=words_df[~words_df.segment.isin(stopwords.stopword)]
    #统计词频
    words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})
    words_stat=words_stat.reset_index().sort_index(by=["计数"],ascending=False)
    print words_stat.head() 

    #用词云进行显示
  
    word_frequence = {x[0]:x[1] for x in words_stat.head(100).values}

  wordcloud=WordCloud(font_path="D:\python\sourcehansansi.ttf",background_color='white',max_font_size=80).generate_from_frequencies(word_frequence)

#这里没有用fit_word
    plt.figure()
    plt.imshow(wordcloud)
    plt.axis("off")
    #plt.savefig()
    plt.show()

    print 'end ...'


#我发现了的问题 

#表情词没有过滤

#如果一句话里面,用户重复了多遍的话,词频就有影响了

#stopwords 应该更加领域化

#wordcloud还可以设置多种样式

#以下是我的结果图








  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 2.7中出现"SyntaxError: invalid syntax"错误通常是因为使用了Python 3.x的语法或者在Python 2.7中使用了不被支持的语法。个错误可能会在使用pip升级或安装第三方库时出现。解决这个问题的方法是: 1. 确保你在Python 2.7的环境中运行代码。你可以通过在终端输入`python --version`来确认当前所使用的Python版本。 2. 检查你的代码,确保其中没有使用Python 3.x的语法。例如,在Python 2.7中,函数定义时不能使用类型注解,例如`def read(rel_path: str) -> str:`。你可以将这样的语法改为`def read(rel_path):`。 3. 确保你正在使用Python 2.7兼容的第三方库版本。有些第三方库可能只支持Python 3.x,所以在Python 2.7中安装可能会导致错误。你可以查阅第三方库的文档,确认其支持的Python版本。 4. 如果你使用的是pip来安装第三方库,确保你在正确的Python环境中运行pip命令。有时候,在安装了多个Python版本的情况下,pip可能会与Python版本不匹配,导致错误。你可以使用绝对路径来运行pip,例如`/path/to/python2.7 -m pip install package_name`。 综上所述,要解决Python 2.7中的"SyntaxError: invalid syntax"错误,你需要确认所运行的代码和所使用的第三方库是兼容的,以及确保在正确的Python环境中运行pip命令。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python 2.7安装pyinstaller报错SyntaxError: invalid syntax](https://blog.csdn.net/lly1122334/article/details/120900986)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [解决pip install xxx报错SyntaxError: invalid syntax的问题](https://download.csdn.net/download/weixin_38506798/14860990)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Python一直报错:SyntaxError: invalid syntax 的原因及解决办法](https://blog.csdn.net/hj960511/article/details/123004813)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值