r - 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
解决方案
使用方法的差异。
str_extract_all
withboundary("word")
删除句子中的标点符号。将文本转换为文档术语矩阵不会。要获得相同的数字,您需要使用DocumentTermMatrix(test1, control = list(removePunctuation = TRUE))
.
详细解释:
在第一种情况下:“这是一个文本。” 将返回没有句点的四个单词。在第二种情况下,您将在文档术语矩阵中获得带有句点(“text.”)的文本。现在,如果文本显示如下:“文本和文本”。第一种情况将计算“文本”= 2,文档术语矩阵将其计算为“文本”= 1 和“文本”。= 1。
使用 removePunction 将删除句点并且计数将相等。
您可能还想先删除数字,因为 removePunctuation 会从数字中删除点和逗号。
推荐阅读
- python - 条件 if else 语句
- jquery - 如何使用初始搜索值启动 select2 脚本
- python - 我无法在 pyttsx3 中更改声音
- html - 移除其他子项时使弹性项目填充可用空间
- javascript - 反应如何在反应库中构建缩小代码
- python - PyMongo 与 Python 中的多处理池
- python - Pygame 类型错误:参数必须是矩形样式对象
- php - MailGun 附件未显示 PHP
- javascript - JSON 对象到数组 Javascript Lodash 解析
- c# - 如果我们在另一个 ListBox 中选择,则清除对一个 ListBox 的选择