首页 > 解决方案 > 在标记 ngram 中检测相同的单词并删除它们

问题描述

在 dfm 中,如何在 ngram 中检测到相同的单词,即

hello_hello, text_text

并将它们从 dfm 中删除?

标签: rquanteda

解决方案


对于您的 ngram 元素由 连接的 dfm,_您可以拆分它们并确定哪些是相同的。

library("quanteda")
## Package version: 2.1.2

dfmat <- dfm(c("test1_test1", "test1_test2", "test2_test2_test2", "test2_other", "other"))

featsplit <- strsplit(featnames(dfmat), "_")
same <- sapply(featsplit, function(y) {
  length(y) >= 2 & # it's a compound (ngram)
    length(unique(y)) == 1 # all elements are the same
})

same
## [1]  TRUE FALSE  TRUE FALSE FALSE

然后,您可以使用它来选择 dfm 中不同的元素:

dfmat[, !same]
## Document-feature matrix of: 5 documents, 3 features (80.0% sparse).
##        features
## docs    test1_test2 test2_other other
##   text1           0           0     0
##   text2           1           0     0
##   text3           0           0     0
##   text4           0           1     0
##   text5           0           0     1

如果您的 ngram 连接器是不同的字符,只需将其替换为_.


推荐阅读