zl程序教程

您现在的位置是:首页 >  其他

当前栏目

微博情感分析代码,随取随用

2023-03-14 22:40:22 时间

情感分析有三种方式。

一是自建模型训练,这种费时费力精度大概率不高。

二是使用百度等在线接口,使用 requests 等请求库调用,精度应该最高,但是这种有并发限制。

三是使用一些开源的模型,比如 SnowNLP 这种,可以直接 pip install,这种精度没有百度的高应该,但是没有接口并发等限制。

其中这三种本质上都是训练好的模型在起作用,第二种是 web sdk,第三种是 local sdk。

本文使用的第三种,需要先 pip 安装 SnowNLP pandas 这两个库。

from snownlp import SnowNLP
import pandas as pd
def sentiment_score(input_file, text_col = 'text'):
    df = pd.read_csv(input_file)
    sentiment_score_col = 'sentiment_score'
    is_scored_col = 'has_scored'
    df[is_scored_col] = [False for _ in range(df.shape[0])]
    for index, row in df.iterrows():
        print(f'{index + 1}/{df.shape[0]}')
        if row[is_scored_col] == True:
            continue
        text = row[text_col]
        # 去除 html 标签
        text = filter_html(text)
        if len(text) == 0 or text == None:
            # 本行没有文本
            sentiment = -1
        else:
            sentiment = SnowNLP(text).sentiments
        df.loc[index, sentiment_score_col] = sentiment
        df.loc[index, is_scored_col] = True

    df.to_csv(input_file, index=False, encoding='utf-8-sig')

上面这个函数的作用是,输入一个 csv 文件名,并且其文本列名为 text,自动输出一个给文本打好情感分的同名 csv 文件。情感分所在列名为 sentiment_score,其值介于 0-1 之间,值小于 0.2 可以判为消极,大于 0.6 可以判为积极。

比如我有一个 12345678.csv 文件,其内容列为 content,可以这样给这个文件打分。

sentiment_score(input_file='12345678.csv', text_col='content')

其中 filter_html 函数 对 html 标签作了过滤。

import re
def filter_html(text):
    # text为包含html标签内容
    content = re.sub("<[^>]*?>", "", text)
    return content

以上所有代码,复制到 py 文件中即可用~