这里要对有关钻石公主号事件的评论做词云分析,通过用户自定义词典和停用词来对评论进行分词
引入包
library(wordcloud2)
library(jiebaR)
library(RColorBrewer)
读入数据并分词。这里我们的数据是每一行为一个评论,一开始我用的read.table和read.csv来读入,以‘’为分隔符,但总出现某个换行以/n的形式出现在数据中,所以我们采用readLines函数来进行数据导入。user.txt是用户自定义词典,用来来保留一些相关词汇,防止像“钻石公主号”这样的词汇被分成“钻石”,“公主”,“号”。
mydata<-readLines(con <- file("comment2.7-2.9.txt", encoding = "UTF-8"))
wk = worker(user='user.txt')
human_future_txt1<-segment(mydata,wk)
过滤掉一个字的词并查看一下剩下多少词
human_future <- subset(human_future_txt1, nchar(human_future_txt1)>1)
length(human_future)
去掉停用词再看剩下多少词,关于停用词也是由一个txt文件存储,同样使用readLines来读入,使用停用词是为了防止像一些特殊符号、数字和“一个”这种没有实际意义的词汇加入到词频统计。
stopwords_CN<-readLines(con <- file("hit_stopwords.txt", encoding = "UTF-8"))
for(j in 1:length(stopwords_CN)){
human_future <- subset(human_future,human_future!=stopwords_CN[j])
}
length(human_future)
进行词频统计和排序,选取最频繁的前100个词来做词云
human_future_freq<-table(human_future)
human_future_freq<-human_future_freq[!grepl('[0-9]+',names(human_future_freq))]
human_future_result<-human_future_freq[order(human_future_freq, decreasing = TRUE)]
human_future_front <- human_future_result[1:100]
最后作词云,颜色这里设置了从一个蓝色主题色系中抽取了颜色较深的前6个,每个颜色有4个,也就是说最频繁的前24个颜色是依次渐浅,剩下的76个设置成天空蓝。结果如图
wordcloud2(human_future_front,
color=c(rep(rev(brewer.pal(9, "Blues"))[1:6],each=4),rep("skyblue",76)),
shape='cardioid',size=0.6,minSize = 0, gridSize = 0,
fontFamily = 'Segoe UI', fontWeight = 'bold',backgroundColor = "white",
minRotation = -pi/4, maxRotation = pi/4, shuffle = TRUE,
rotateRatio = 0.4, ellipticity = 0.65)