首页 > 解决方案 > VCorpus 和 DTM 中的词频不匹配

问题描述

我计算了来自 Corpus 和 DTM 的测试文档的词频如下。但他们彼此并不匹配。谁能告诉我不匹配来自哪里?是不是因为我用了错误的方法来提取词频?

library("tm")
library("stringr")
library("dplyr")
test1 <- VCorpus(DirSource("test_papers"))
mytable1 <- lapply(test1, function(x){str_extract_all(x, boundary("word"))}) %>% unlist() %>% table() %>% sort(decreasing=T)
test2 <- DocumentTermMatrix(test1)
mytable2 <- apply(test2, 2, sum) %>% sort(decreasing=T)
head(mytable1)
.
and  of the  to  in  on 
148 116 111  69  61  54 
head(mytable2)
      and       the      this      that       are political 
      145       120        35        34        33        33 

标签: rtext-miningtmcorpus

解决方案


使用方法的差异。

str_extract_allwithboundary("word")删除句子中的标点符号。将文本转换为文档术语矩阵不会。要获得相同的数字,您需要使用DocumentTermMatrix(test1, control = list(removePunctuation = TRUE)).

详细解释:

在第一种情况下:“这是一个文本。” 将返回没有句点的四个单词。在第二种情况下,您将在文档术语矩阵中获得带有句点(“text.”)的文本。现在,如果文本显示如下:“文本和文本”。第一种情况将计算“文本”= 2,文档术语矩阵将其计算为“文本”= 1 和“文本”。= 1。

使用 removePunction 将删除句点并且计数将相等。

您可能还想先删除数字,因为 removePunctuation 会从数字中删除点和逗号。


推荐阅读