【问题标题】:stemDocument works in TermDocumentMatrix but does not work in tm_map using tm and RstemDocument 在 TermDocumentMatrix 中有效,但在使用 tm 和 R 的 tm_map 中无效
【发布时间】:2016-11-07 06:32:25
【问题描述】:

假设有一个字符串“彩色铅笔 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 适用于有色和颜色,两者都变成了颜色。但是,如果我这样做:

> 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 在这里不起作用。我注意到这里有“字符(0)”,上面的矩阵中没有显示。但是不知道为什么?

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

【问题讨论】:

    标签: r tm


    【解决方案1】:

    这应该可以帮助您实现您想要的,我通常在创建 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。

    希望这会有所帮助。

    【讨论】:

    • 非常感谢。这行得通。但是有些奇怪。看起来 txt
    猜你喜欢
    • 2012-03-27
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多