-1

我有一个包含 200 多个 pdf 的数据集,我将其转换为语料库。我正在使用 R 的 TM 包进行文本预处理和挖掘。到目前为止,我已经成功创建了 DTM(文档术语矩阵),并且可以找到 x 个最常出现的术语。然而,我研究的目标是检查语料库中是否使用了某些术语。我不是在寻找最常见的术语,而是有我自己的术语列表,我想检查它们是否出现,如果是,出现了多少次。

到目前为止,我已经尝试过:

function <- content_transformer(function(x, pattern)regmatches(x,gregexpr(pattern, x, perl=TRUE, ignore.case = TRUE)))
keep = "word_1|word_2"
tm_map(my_corpus, function, keep)[[1]]

还有这些:

str_detect(my_corpus, "word_1", "word_2" )
str_locate_all(my_corpus, "word_1", "word_2")
str_extract(my_corpus, "funds")

最后一个似乎最接近输出:[1] "funds" NA NA

似乎两者都没有给我我需要的东西。

4

1 回答 1

2

dictionary您可以在创建 DocumentTermMatrix 时使用该选项。在示例代码中查看它是如何工作的。一旦进入 documenttermmatrix 表单或 data.frame 表单,如果您不需要每个文档的字数,您可以使用聚合函数。

library(tm)

data("crude")
crude <- as.VCorpus(crude)
crude <- tm_map(crude, content_transformer(tolower))

my_words <- c("oil", "corporation")

dtm <- DocumentTermMatrix(crude, control=list(dictionary = my_words))

# create data.frame from documenttermmatrix
df1 <- data.frame(docs = dtm$dimnames$Docs, as.matrix(dtm), row.names = NULL)
head(df1)
   docs corporation oil
1   127           0   5
2   144           0  11
3   191           0   2
4   194           0   1
5   211           0   1
6   236           0   7
于 2018-07-30T16:09:14.050 回答