stemDocument 在 TermDocumentMatrix 中有效,但在 tm_map 中使用 tm 和 R 无效

stemDocument works in TermDocumentMatrix but does not work in tm_map using tm and R

假设有一个字符串"COLORED PENCIL STAEDTLER NORIS CLUB ASSORTED COLORS PKT12"。我的代码是:

> a1 <- VCorpus(VectorSource("COLORED PENCIL STAEDTLER NORIS CLUB ASSORTED COLORS PKT12"))
> a3 <- TermDocumentMatrix(a1,control = list(stemming=T))

矩阵为:

           Docs
Terms       1
  assort    1
  club      1
  color     2
  nori      1
  pencil    1
  pkt12     1
  staedtler 1

因此我们可以看到 stemDocument 对 colored 和 colors 起作用,它们都变成了 color。但是,如果我这样做:

> a1 <- VCorpus(VectorSource("COLORED PENCIL STAEDTLER NORIS CLUB ASSORTED COLORS PKT12"))
> a2 <- a1 %>% tm_map(PlainTextDocument) %>% tm_map(stemDocument,"english")
> a2[[1]]$content
[1] "COLORED PENCIL STAEDTLER NORIS CLUB ASSORTED COLORS PKT12"
> a2 <- a2 %>% TermDocumentMatrix()

矩阵为:

           Docs
Terms       character(0)
  assorted             1
  club                 1
  colored              1
  colors               1
  noris                1
  pencil               1
  pkt12                1
  staedtler            1

我们可以看到 stemDocument 在这里不起作用。我注意到这里有 "character(0)" ,上面的矩阵中没有显示。但是不知道为什么?

我的情况是我需要对停用词、stemDocument 等文本数据进行一些预处理。然后我需要将这个处理过的文本保存到一个 csv 文件中。所以这里我不能直接使用TermDocumentMatrix来生成矩阵。有人可以帮我吗?非常感谢。

这应该可以帮助您实现您想要的效果,我通常会在创建 dtm/tdm

之前将所有文本转换为小写,删除标点符号等
library(tm)
txt <- "COLORED PENCIL STAEDTLER NORIS CLUB ASSORTED COLORS PKT12"

txt <- tolower(txt) ## this is the extra step where I have converted eveything to lower case 

a1 <- VCorpus(VectorSource(txt))
a2 <- a1 %>%  tm_map(stemDocument) 
a2 <- a2 %>% TermDocumentMatrix()
inspect(a2)

character(0) 出现是因为调用了PlainTextDocument()。在需要使用它的情况下,例如当您使用 pass tolower 到 tm_map 并收到此错误 - Error: inherits(doc, "TextDocument") is not TRUE 时,请使用 content_transformer.

希望对您有所帮助。