我有一个庞大的语料库,我只对我预先知道的少数术语的出现感兴趣。有没有办法使用tm
包从语料库创建术语文档矩阵,其中只有我预先指定的术语才能使用和包含?
我知道我可以对语料库的结果 TermDocumentMatrix 进行子集化,但由于内存大小限制,我想避免从构建完整的术语文档矩阵开始。
我有一个庞大的语料库,我只对我预先知道的少数术语的出现感兴趣。有没有办法使用tm
包从语料库创建术语文档矩阵,其中只有我预先指定的术语才能使用和包含?
我知道我可以对语料库的结果 TermDocumentMatrix 进行子集化,但由于内存大小限制,我想避免从构建完整的术语文档矩阵开始。
您可以通过构建自定义转换函数来修改语料库以仅保留所需的术语。有关更多信息,请参阅包的Vignettetm
content_transformer
和函数的帮助:
library(tm)
# Create a corpus from the text listed below
corp = VCorpus(VectorSource(doc))
# Custom function to keep only the terms in "pattern" and remove everything else
(f <- content_transformer(function(x, pattern)
regmatches(x, gregexpr(pattern, x, perl=TRUE, ignore.case=TRUE))))
(仅供参考,上面的第二行代码改编自this SO answer。)
# The pattern we'll search for
keep = "sleep|dream|die"
# Run the transformation function using the pattern above
tm_map(corp, f, keep)[[1]]
这是运行转换函数的结果:
<<PlainTextDocument (metadata: 7)>>
c("die", "sleep", "sleep", "die", "sleep", "sleep", "Dream")
这是我用来创建语料库的原文:
doc = "To be, or not to be, that is the question—
Whether 'tis Nobler in the mind to suffer
The Slings and Arrows of outrageous Fortune,
Or to take Arms against a Sea of troubles,
And by opposing, end them? To die, to sleep—
No more; and by a sleep, to say we end
The Heart-ache, and the thousand Natural shocks
That Flesh is heir to? 'Tis a consummation
Devoutly to be wished. To die, to sleep,
To sleep, perchance to Dream; Aye, there's the rub"
另一种过滤语料库的方法;首先将您的值分配给元部分,例如语言;通过使用变量i循环语料库的元素,检查您想要的任何内容,然后使用这些元属性进行过滤。
corpusz[[i]]$meta["language"] <- 'tur'
idx <- meta(corpusz, "language") == 'tur'
filtered <- corpusz[idx]
现在过滤后只包含我们想要的语料库元素。