计算新闻传播学临摹作业_数据抓取与数据清洗(西安交大国家艺术基金数据可视化培训第34天)

一 基于字典的情感分析

1 Jieba中文分词

算法设计[邓旭东]

  • 第一步:读取评论数据,对评论进行分句。
  • 第二步:查找对分句的情感词,记录积极还是消极,以及位置。
  • 第三步:往情感词前查找程度词,找到就停止搜寻。为程度词设权值,乘以情感值
  • 第四步:往情感词前查找否定词,找完全部否定词,若数量为奇数,乘以-1,若为偶数,乘以1。
  • 第五步:判断分句结尾是否有感叹号,有叹号则往前寻找情感词,有则相应的情感值+2。
  • 第六步:计算完一条评论所有分句的情感值,用数组(list)记录起来。
  • 第七步:计算并记录所有评论的情感值。
  • 第八步:通过分句计算每条评论的积极情感均值,消极情感均值,积极情感方差,消极情感方差。

TextBlob

  • TextBlob是一个用Python编写的开源的文本处理库。它可以用来执行很多自然语言处理的任务,比如,词性标注,名词性成分提取,情感分析,文本翻译,等等。
  • Github地址:
  • 安装
    pip install textblob
    测试:
    #TextBlob简介
    from textblob import TextBlob
    testimonial = TextBlob("Textblob is amazingly simple to use. What great fun!")
    print(testimonial.sentiment)

    安装语料库
    import nltk
    nltk.download()
    测试:[源码:textblob官方]

    #测试Brown Corpus
    from nltk.corpus import brown
    brown.words()
    # 测试词性标注
    from textblob import TextBlob
    wiki = TextBlob("Python is a high-level, general-purpose programming language.")
    wiki.tags

    案例:基于词典的情绪分析[源码:邓旭东]
     

    # 哈工大邓旭东老师的代码
    # 哈尔滨工业大学 管理科学与工程博士在读
    #知乎   https://zhuanlan.zhihu.com/p/23225934
    import jieba
    import numpy as np
    
    #打开词典文件,返回列表
    #注意:那是函数中关键词参数,随便起的。后边调用这个函数时会有真正有用的名字传进来
    def open_dict(Dict = 'hahah', path=r'/Users/apple888/PycharmProjects/Textming/Sent_Dict/Hownet/'):
        path = path + '%s.txt' % Dict
        dictionary = open(path, 'r', encoding='utf-8')
        dict = []
        for word in dictionary:
            word = word.strip('\n')
            dict.append(word)
        return dict
    
    def judgeodd(num):
        if (num % 2) == 0:
            return 'even'
        else:
            return 'odd'
    
    #设置path路径。
    deny_word = open_dict(Dict = '否定词', path= r'')
    posdict = open_dict(Dict = 'positive', path= r'')
    negdict = open_dict(Dict = 'negative', path= r'')
    
    degree_word = open_dict(Dict = '程度级别词语', path= r'')
    mostdict = degree_word[degree_word.index('extreme')+1 : degree_word.index('very')]#权重4,即在情感词前乘以3
    verydict = degree_word[degree_word.index('very')+1 : degree_word.index('more')]#权重3
    moredict = degree_word[degree_word.index('more')+1 : degree_word.index('ish')]#权重2
    ishdict = degree_word[degree_word.index('ish')+1 : degree_word.index('last')]#权重0.5
    
    def sentiment_score_list(dataset):
        seg_sentence = dataset.split('。')
    
        count1 = []
        count2 = []
        for sen in seg_sentence: #循环遍历每一个评论
            segtmp = jieba.lcut(sen, cut_all=False)  #把句子进行分词,以列表的形式返回
            i = 0 #记录扫描到的词的位置
            a = 0 #记录情感词的位置
            poscount = 0 #积极词的第一次分值
            poscount2 = 0 #积极词反转后的分值
            poscount3 = 0 #积极词的最后分值(包括叹号的分值)
            negcount = 0
            negcount2 = 0
            negcount3 = 0
            for word in segtmp:
                if word in posdict:  # 判断词语是否是情感词
                    poscount += 1
                    c = 0
                    for w in segtmp[a:i]:  # 扫描情感词前的程度词
                        if w in mostdict:
                            poscount *= 4.0
                        elif w in verydict:
                            poscount *= 3.0
                        elif w in moredict:
                            poscount *= 2.0
                        elif w in ishdict:
                            poscount *= 0.5
                        elif w in deny_word:
                            c += 1
                    if judgeodd(c) == 'odd':  # 扫描情感词前的否定词数
                        poscount *= -1.0
                        poscount2 += poscount
                        poscount = 0
                        poscount3 = poscount + poscount2 + poscount3
                        poscount2 = 0
                    else:
                        poscount3 = poscount + poscount2 + poscount3
                        poscount = 0
                    a = i + 1  # 情感词的位置变化
    
                elif word in negdict:  # 消极情感的分析,与上面一致
                    negcount += 1
                    d = 0
                    for w in segtmp[a:i]:
                        if w in mostdict:
                            negcount *= 4.0
                        elif w in verydict:
                            negcount *= 3.0
                        elif w in moredict:
                            negcount *= 2.0
                        elif w in ishdict:
                            negcount *= 0.5
                        elif w in degree_word:
                            d += 1
                    if judgeodd(d) == 'odd':
                        negcount *= -1.0
                        negcount2 += negcount
                        negcount = 0
                        negcount3 = negcount + negcount2 + negcount3
                        negcount2 = 0
                    else:
                        negcount3 = negcount + negcount2 + negcount3
                        negcount = 0
                    a = i + 1
                elif word == '!' or word == '!':  ##判断句子是否有感叹号
                    for w2 in segtmp[::-1]:  # 扫描感叹号前的情感词,发现后权值+2,然后退出循环
                        if w2 in posdict or negdict:
                            poscount3 += 2
                            negcount3 += 2
                            break
                i += 1 # 扫描词位置前移
    
    
                # 以下是防止出现负数的情况
                pos_count = 0
                neg_count = 0
                if poscount3 < 0 and negcount3 > 0:
                    neg_count += negcount3 - poscount3
                    pos_count = 0
                elif negcount3 < 0 and poscount3 > 0:
                    pos_count = poscount3 - negcount3
                    neg_count = 0
                elif poscount3 < 0 and negcount3 < 0:
                    neg_count = -poscount3
                    pos_count = -negcount3
                else:
                    pos_count = poscount3
                    neg_count = negcount3
    
                count1.append([pos_count, neg_count])
            count2.append(count1)
            count1 = []
    
        return count2
    
    def sentiment_score(senti_score_list):
        score = []
        for review in senti_score_list:
            score_array = np.array(review)
            Pos = np.sum(score_array[:, 0])
            Neg = np.sum(score_array[:, 1])
            AvgPos = np.mean(score_array[:, 0])
            AvgPos = float('%.1f'%AvgPos)
            AvgNeg = np.mean(score_array[:, 1])
            AvgNeg = float('%.1f'%AvgNeg)
            StdPos = np.std(score_array[:, 0])
            StdPos = float('%.1f'%StdPos)
            StdNeg = np.std(score_array[:, 1])
            StdNeg = float('%.1f'%StdNeg)
            score.append([Pos, Neg, AvgPos, AvgNeg, StdPos, StdNeg])
        return score
    
    data = '你就是个王八蛋,混账玩意!你们的手机真不好用!非常生气,我非常郁闷!!!!'
    data2= '我好开心啊,非常非常非常高兴!今天我得了一百分,我很兴奋开心,愉快,开心'
    
    print(sentiment_score(sentiment_score_list(data)))
    print(sentiment_score(sentiment_score_list(data2)))

     

 

2 SnowNLP

    SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个方便处理中文的类库,并且和TextBlob不同的是,这里没有用NLTK,所有的算法都是自己实现的,并且自带了一些训练好的字典。注意本程序都是处理的unicode编码,所以使用时请自行decode成unicode。

3 PaddleHub

     基于PaddlePaddle生态下的预训练模型管理和迁移学习工具,可以结合预训练模型更便捷地开展迁移学习工作。通过PaddleHub,可以便捷地获取PaddlePaddle生态下的所有预训练模型,涵盖了图像分类、目标检测、词法分析、语义模型、情感分析、语言模型、视频分类、图像生成八类主流模型。通过PaddleHub Fine-tune API,结合少量代码即可完成大规模预训练模型的迁移学习。PaddleHub引入『模型即软件』的设计理念,支持通过Python API或者命令行工具,一键完成预训练模型地预测,更方便的应用PaddlePaddle模型库。


二 推荐系统简介

推荐系统的类型

社会化推荐(Social Recommendation)、基于内容的推荐 (Content-based filtering)、基于协同过滤的推荐(collaborative filtering)

协同过滤算法

基于邻域的方法(neighborhood-based method)(包括user-based filtering、item-based filtering)、隐语义模型(latent factor model)、基于图的随机游走算法(random walk on graphs)

UserCF和ItemCF的比较

  • UserCF较为古老, 1992年应用于电子邮件个性化推荐系统Tapestry, 1994年应用于Grouplens新闻个性化推荐, 后来被Digg采用
  • ItemCF相对较新,应用于电子商务网站Amazon和DVD租赁网站Netflix
  • 新闻更新快,物品数量庞大,相似度变化很快,不利于维护一张物品相似度的表格,电影、音乐、图书则可以。

推荐系统评测

用户满意度、预测准确度

案例:推荐系统简介[源码:Toby Segaran]
 

# A dictionary of movie critics and their ratings of a small
# set of movies
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
      'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
      'The Night Listener': 3.0},
     'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
      'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
      'You, Me and Dupree': 3.5},
     'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
      'Superman Returns': 3.5, 'The Night Listener': 4.0},
     'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
      'The Night Listener': 4.5, 'Superman Returns': 4.0,
      'You, Me and Dupree': 2.5},
     'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
      'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
      'You, Me and Dupree': 2.0},
     'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
      'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
     'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}

critics['Toby']

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值