r-文字词干后不准确的单词频率



感谢您抽出宝贵的时间阅读我的帖子。Newbie在这里,这是我的第一个R脚本,其中包含一些示例数据。

library(tm)
library(hunspell)
library(stringr)
docs <- VCorpus(VectorSource('He is a nice player, She could be a better player. Playing basketball is fun. Well played! We could have played better. Wish we had better players!'))
input <- strsplit(as.character(docs), " ")
input <- unlist(input)
input <- hunspell_stem(input)
input <- word(input,-1)
input <- VCorpus(VectorSource(input))
docs <- input
docs <- tm_map(docs, content_transformer(tolower))
docs <- tm_map(docs, removeWords, stopwords("english"))
docs <- tm_map(docs, removePunctuation)
docs <- tm_map(docs, stripWhitespace)
dtm <- TermDocumentMatrix(docs)
m <- as.matrix(dtm)
sort(rowSums(m),decreasing=TRUE)

这返回以下结果:

字符0 48更好3玩3篮球1描述1
娱乐1头1小时1语言1 meta 1 min 1好1 来源1井1愿望1年1

预期结果:

更好3玩3篮球1娱乐1语言1好1井1 希望1

不确定这些单词来自何处(字符0,描述,元语言,语言等),如果有办法摆脱它们?

基本上,我要做的是用hunspell将stems应用于语料库(数据源SQL Server表),并以后将其显示在Word Cloud中。任何帮助,将不胜感激。GD

这就是您评论中的示例失败的原因:

library(tm) 
library(hunspell) 
hunspell_stem(strsplit('Thanks lukeA for your help!', "\W")[[1]])
# [[1]]
# [1] "thank"
# 
# [[2]]
# character(0)
# 
# [[3]]
# [1] "for"
# 
# [[4]]
# [1] "your"
# 
# [[5]]
# [1] "help"

这是使它起作用的一种方法:

docs <- VCorpus(VectorSource('Thanks lukeA for your help!')) 
myStem <- function(x) { 
  res <- hunspell_stem(x)
  idx <- which(lengths(res)==0)
  if (length(idx)>0)
    res[idx] <- x[idx]
  sapply(res, tail, 1) 
}
dtm <- TermDocumentMatrix(docs, control = list(stemming = myStem)) 
m <- as.matrix(dtm) 
sort(rowSums(m),decreasing=TRUE)
  # for help! lukea thank  your 
  #   1     1     1     1     1 

如果没有茎,这将返回原始令牌,如果有多个茎,则将返回最后一个茎。

最新更新