经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » R语言 » 查看文章
Word Cloud (词云) - R
来源:cnblogs  作者:yukiwu  时间:2019/6/6 8:54:22  对本文有异议

在前面已经陆续总结了如何用 PythonJavaScript 创建词云了,今天要说的是 R。其实 SPSS 和 SAS 的 Word Cloud 扩展模板都是基于 R 实现的。

Create Word Cloud via R

1) 准备文本。

我们再…再次使用上次保存的 Word Cloud History.txt 的文本,这样我们就可以在最后比较用各种方法生成词云的效果。(好吧,其实主要是懒,继续用吧……)

2) 安装并加载所需的 R 包。

  1. # Install
  2. install.packages("tm") # for text mining
  3. install.packages("wordcloud") # word-cloud generator
  4. install.packages("RColorBrewer") # color palettes
  5. # Load
  6. library("tm")
  7. library("wordcloud")
  8. library("RColorBrewer")

3) 读取并清洗文本数据。读取数据完毕我们可以用 inspect() 来查看是否读取文本成功。

  1. #Read text file
  2. text <- readLines(file.choose())
  3. # Load the data as a corpus
  4. docs <- Corpus(VectorSource(text))
  5. #Inspect the content
  6. #inspect(docs)[1:10]

4) 清洗数据。我们将使用 tm_map() 函数来进行文本的大小写转换,清洗文本的空格符,常见停用词等。

  1. # Convert the text to lower case
  2. docs <- tm_map(docs, content_transformer(tolower))
  3. # Remove numbers
  4. docs <- tm_map(docs, removeNumbers)
  5. # Remove english common stopwords
  6. docs <- tm_map(docs, removeWords, stopwords("english"))
  7. # Remove punctuations
  8. docs <- tm_map(docs, removePunctuation)
  9. # Eliminate extra white spaces
  10. docs <- tm_map(docs, stripWhitespace)

5) 用文本数据生成矩阵存放词语 (words) 及其频率 (frequencies) 。其中所用的 TermDocumentMatrix() 来自于 text mining 程序包。转换后我们可以用 head() 来查看矩阵数据。

  1. #Convert this into a matrix format
  2. m <- as.matrix(dtm)
  3. #Gives you the frequencies for every word
  4. v <- sort(rowSums(m),decreasing=TRUE)
  5. d <- data.frame(word = names(v),freq=v)
  6. #Scan the data
  7. #head(d, 10)

6) 生成 word cloud。

  1. wordcloud(words = d$word, freq = d$freq, scale=c(5,0.5), min.freq = 1,
  2. max.words=200, random.order=FALSE, rot.per=0.35,
  3. colors=brewer.pal(8, "Accent"))

Word Cloud R

Notes

如果要查看 wordcloud() 函数的各个参数的意义或者想给图形换个颜色,敲 help(wordcloud) 或者 help(RColorBrewer) 就可以查看帮助文档啦。

Sample Code

download here

原文链接:http://www.cnblogs.com/yukiwu/p/10969250.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号