zoukankan      html  css  js  c++  java
  • R——启程——豆瓣影评分析

        专业统计的我,自然免不了学R的,今天仔细看了这篇教程(感谢学姐的推荐@喜欢算法的女青年),就学着用R仿照着做一个,作为R语言学习的起点吧。

    影评数据是用python爬的,之后会在python爬虫系列补充上爬虫程序。

        这里选取的影片是《完美陌生人》,豆瓣评分挺高的,并未看过。。。。爬好的数据为了方便同样写入xlsx文件。这里直接将xlsx后缀改为csv,方便导入R。

    原始的EXCEL文件是这样的:

        接下来,就是导入数据,并分析了,这里差不多全是抄的上面提到教程的代码,就贴一下,不在赘述。

    data <- read.csv("完美陌生人.csv", header=T)
    
    # 日期处理
    date <- as.Date(data$date)
    plot(table(as.Date(date)), xlab = "评论日期",
         ylab = "评论数量", main = "《完美陌生人》豆瓣短评评论趋势", col = 2:5)
    
    star <- data$star
    starx <- sort(table(star), decreasing = T)
    na <- length(star) - sum(starx)
    # paste拼接字符串; round控制小数位数
    print(paste("参与评分人数--->",sum(starx),"约占总人数的",round(sum(starx)/length(star),4)))
    rate = starx/sum(starx)
    par(mar = c(0,1,2,1))
    pie(rate, labels = paste(names(rate)," 星 ",
        format(rate * 100,digits=3),"%",sep=''),col=rainbow(5))
    

      输出如下:

    输出打印信息:

        在按照教程操作时,遇到一个问题,就是那个Rwordseg包无法Install,这里请参考这篇文章,感谢作者,问题得到解决。

    这是关于分词的代码:

    # 分词分析
    comment <- data$comment
    short <- data[is.na(comment)&nchar(comment)>1,]
    comment <- as.character(data$comment)
    cmt.len <- nchar(comment)
    
    par(mar=c(5,2,2,1))
    hist(cmt.len,freq=F,ylim=c(0,0.025),col = "goldenrod2",
         xlab="短评文本的长度",main="短评长度的分布直方图")
    lines(density(cmt.len), col = 'tomato')
    
    
    f_cut <- function(x) {
      library(Rwordseg)
      unlist(strsplit(segmentCN(x, nature = T), " "))
    }
    # 定义词语长度至少为2
    word_cut <- function(x, n = 1) {
      x <- gsub("[a-z]|\.", "", x)
      x[nchar(x) > n]
    }
    comment.words <- lapply(comment, f_cut)
    words <- lapply(comment.words, word_cut, 1)  
    
    # 去掉words词汇量为0的文本
    cw.len <- unlist(lapply(words,length))
    short2 <- data[cw.len > 0,]
    
    star2 <- short2$star
    words2 <- words[cw.len > 0]
    cw.len <- cw.len[cw.len > 0]
    
    par(mar=c(5,2,2,1))
    hist(cw.len,freq=F,ylim=c(0,0.096),col='chocolate2',
         main="短评词汇数量分布直方图",xlab="短评词汇数量")
    lines(density(cw.len), col="red")
    

      输出如下:

        在看到词云时,实在有些懵,打算另寻其他方法,于是就有了wordcloud2的登场。

    # 词频统计
    all.words <- unlist(words2)
    all_freq <- as.data.frame(table(all.words))
    wordcloud2(all_freq)
    

      简单几行代码搞定!而且效果也很好。

    all_freq的格式:

     最后词云图:

        词云图也是可以显示数据的:

        到这里,算是对影评有了一个初步的分析了,R果然强大啊。

  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/buzhizhitong/p/5813228.html
Copyright © 2011-2022 走看看