Skip to content

python使用snownlp对中文语句进行情感分析/自定义训练使用

安装snownlp

shell
pip install snownlp -i https://pypi.tuna.tsinghua.edu.cn/simple

使用自带的训练集进行测试

python
from snownlp import SnowNLP

def sentiment_analysis(text):
    # 使用SnowNLP对中文文本进行情感分析
    s = SnowNLP(text)
    # SnowNLP的sentiments方法返回情感倾向分数,越接近1表明情感越积极,越接近0表明情感越消极
    sentiment_score = s.sentiments
    return sentiment_score

if __name__ == '__main__':
    text = "角色塑造太单调,毫无震撼力!"
    score = sentiment_analysis(text)
    print(f"情感分数: {score}")
    if score > 0.5:
        print("该语句是积极的。")
    else:
        print("该语句是消极的。")

使用自定义的语料库训练并使用

python
from snownlp import SnowNLP
from snownlp import sentiment

# 判定语句的情感值
def sentiment_analysis(text):
    # 使用SnowNLP对中文文本进行情感分析
    s = SnowNLP(text)
    # SnowNLP的sentiments方法返回情感倾向分数,越接近1表明情感越积极,越接近0表明情感越消极
    sentiment_score = s.sentiments
    return sentiment_score

# 准备两个文件pos.txt 积极性文件 neg.txt 消极性文件
# 训练数据,会生成一个sentiment.marshal.3 文件,将这个文件替换掉安装包的文件就可以使用自定义的训练集数据
def train_self_model():
    pos = "./pos.txt"
    neg = "./neg.txt"
    sentiment.train(neg, pos)
    sentiment.save("sentiment.marshal")

# 查找安装包位置
def get_site_pkg_path():
    import site
    return site.getsitepackages()[0]

if __name__ == '__main__':
    text = "角色塑造太单调,毫无震撼力!"
    score = sentiment_analysis(text)
    print(f"情感分数: {score}")
    if score > 0.5:
        print("该语句是积极的。")
    else:
        print("该语句是消极的。")

    # 训练
    # train_self_model()

    # 查找安装包的位置
    # print(get_site_pkg_path())