NGramTokenizer没有按预期工作

时间:2017-03-01 17:28:30

标签: r ggplot2 n-gram

我有一个简单的R代码,我正在从文件中读取文本并在条形图上绘制重复的短语。出于某种原因,条形图仅显示单个单词而不是多个措辞短语。我哪里错了?

install.packages("xlsx")
install.packages("tm")
install.packages("wordcloud")
install.packages("ggplot2")

library(xlsx)
library(tm)
library(wordcloud)
library(ggplot2)

setwd("C://Users//608447283//desktop//R_word_charts")


test <- Corpus(DirSource"C://Users//608447283//desktop//R_word_charts//source"))

test <- tm_map(test, stripWhitespace)
test <- tm_map(test, tolower)
test <- tm_map(test, removeWords,stopwords("english"))
test <- tm_map(test, removePunctuation)
test <- tm_map(test, PlainTextDocument)

tok <- function(x) NGramTokenizer(x, Weka_control(min=3, max=10))
tdm <- TermDocumentMatrix(test,control = list(tokenize = tok))
termFreq <- rowSums(as.matrix(tdm))

termFreq <- subset(termFreq, termFreq>=50)

write.csv(termFreq,file="TestCSV1")
TestCSV <- read.csv("C:/Users/608447283/Desktop/R_word_charts/TestCSV1")

ggplot(data=TestCSV, aes(x=X, y=x)) +
  geom_bar(stat="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1))

我的输出:

enter image description here

示例数据: Sample data extract

2 个答案:

答案 0 :(得分:6)

最新版本的tm软件包(版本0.7)似乎存在问题。

回到版本0.6-2应解决1克问题。

另一个问题可能是您的数据子集。

过滤器(termFreq <- subset(termFreq, termFreq>=50))过于宽松,过滤掉了许多有价值的N-Grams。我宁愿使用前N种可视化数据的方法。即:

library(tm)
library(ggplot2)
library(RWeka)
library(data.table)
library(dplyr)

setwd(dir = "/home/eliasah/Downloads/")
test <- Corpus(DirSource("/home/eliasah/Downloads/sample/"))

test <- tm_map(test, stripWhitespace)
test <- tm_map(test, tolower)
test <- tm_map(test, removeWords,stopwords("english"))
test <- tm_map(test, removePunctuation)
test <- tm_map(test, PlainTextDocument)

tok <- function(x) NGramTokenizer(x, Weka_control(min=3, max=10))
tdm <- TermDocumentMatrix(test,control = list(tokenize = tok))
termFreq <- rowSums(as.matrix(tdm))
termFreqVector <- as.list(termFreq)

test2 <- data.frame(unlist(termFreqVector), stringsAsFactors=FALSE)
setDT(test2, keep.rownames = TRUE)[]
setnames(test2, 1, "term")
setnames(test2, 2, "freq")
test3 <- head(arrange(test2,desc(freq)), n = 30)

ggplot(data=test3, aes(x=reorder(term, freq), y=freq)) + geom_bar(stat="identity") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + coord_flip()

enter image description here

我希望这可以帮助您解决问题。

注意:我使用了您在问题中链接的数据样本。

答案 1 :(得分:2)

包还在那里!但是在从“ tm”软件包中询问了这些人之后,我使用了“ VCorpus”而不是“ Corpus”,现在它可以正常工作了。

相关问题