关于python:王力宏的瓜很大我用Python爬取了瓜文评论区发现更精彩

8次阅读

共计 2661 个字符,预计需要花费 7 分钟才能阅读完成。

早上关上微博一看,WC,微博推给我的第一条就是一篇瓜文。

于是纯熟的找到了瓜文出处,根本状况就是力宏前妻忍气吞声,于是发文手撕力宏 … 博文如下:

开始,我还有些纳闷,前两天力宏是抵赖了离婚并发了博文:

博文中透漏的齐全是一副好聚好散,岁月静好的氛围,如同用词有点不当了,不过也不纠结这些了。

自己虽不追星,对各种大小明星也根本无感,但也是很多年前就在娃哈哈的矿泉水瓶上晓得力宏这号人物了 …

记不清是什么工夫了,娃哈哈换掉了代言人力宏,过后网络上还是一片声讨,当初看来 …

于是我带着吃瓜大众的好奇心读了李靓蕾的微博撕文,WC,真是欠力宏一座奥斯卡 …

如此瓜文,怎么能放过评论区呢 … 于是我筹备用 Python 爬取评论区数据,次要代码实现如下:

# 爬取一页评论内容
def get_one_page(url):
    headers = {'User-agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3880.4 Safari/537.36',
        'Host' : 'weibo.cn',
        'Accept' : 'application/json, text/plain, */*',
        'Accept-Language' : 'zh-CN,zh;q=0.9',
        'Accept-Encoding' : 'gzip, deflate, br',
        'Cookie' : '本人的 Cookie',
        'DNT' : '1',
        'Connection' : 'keep-alive'
    }
    # 获取网页 html
    response = requests.get(url, headers = headers, verify=False)
    # 爬取胜利
    if response.status_code == 200:
        # 返回值为 html 文档,传入到解析函数当中
        return response.text
    return None

# 解析保留评论信息
def save_one_page(html):
    comments = re.findall('<span class="ctt">(.*?)</span>', html)
    for comment in comments[1:]:
        result = re.sub('<.*?>', '', comment)
        if '回复 @' not in result:
            with open('comments.txt', 'a+', encoding='utf-8') as fp:
                fp.write(result)

爬取剖析过程这里就不说了,不分明的能够看一下:微博评论区爬取,数据有了,当初咱们再用 Python 来看一下 TOP10 词汇有哪些,次要代码实现如下:

stop_words = []
with open('stop_words.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        stop_words.append(line.strip())
content = open('comments.txt', 'rb').read()
# jieba 分词
word_list = jieba.cut(content)
words = []
for word in word_list:
    if word not in stop_words:
        words.append(word)

wordcount = {}
for word in words:
    if word != ' ':
        wordcount[word] = wordcount.get(word, 0)+1
wordtop = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10]
wx = []
wy = []
for w in wordtop:
    wx.append(w[0])
    wy.append(w[1])

(Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
    .add_xaxis(wx)
    .add_yaxis('数量', wy)
    .reversal_axis()
    .set_global_opts(title_opts=opts.TitleOpts(title='评论词 TOP10'),
        yaxis_opts=opts.AxisOpts(name='词语'),
        xaxis_opts=opts.AxisOpts(name='数量'),
        )
    .set_series_opts(label_opts=opts.LabelOpts(position='right'))
).render_notebook()

看一下成果:

这里咱们不做评论了,接着再生成词云看看评论区,次要代码实现如下:

def jieba_():
    stop_words = []
    with open('stop_words.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            stop_words.append(line.strip())
    content = open('comments.txt', 'rb').read()
    # jieba 分词
    word_list = jieba.cut(content)
    words = []
    for word in word_list:
        if word not in stop_words:
            words.append(word)
    global word_cloud
    # 用逗号隔开词语
    word_cloud = ','.join(words)

def cloud():
    # 关上词云背景图
    cloud_mask = np.array(Image.open('bg.png'))
    # 定义词云的一些属性
    wc = WordCloud(
        # 背景图宰割色彩为红色
        background_color='white',
        # 背景图样
        mask=cloud_mask,
        # 显示最大词数
        max_words=200,
        # 显示中文
        font_path='./fonts/simhei.ttf',
        # 最大尺寸
        max_font_size=100
    )
    global word_cloud
    # 词云函数
    x = wc.generate(word_cloud)
    # 生成词云图片
    image = x.to_image()
    # 展现词云图片
    image.show()
    # 保留词云图片
    wc.to_file('melon.png')

看一下成果:

源码曾经整顿好了,有须要的能够在公众号 Python 小二 后盾回复 wlh 获取。

正文完
 0