从发表答案:将文档ID与R语料库保持@MrFlick保留来自R corpus的确切单词
我想略微修改一个很好的例子。
问题:如何修改content_transformer
功能只保留确切话吗?您可以在检查输出中看到奇妙的计数为奇迹和比率计为基本原理。我对gregexpr
和regmatches
没有深入的了解。
创建数据帧:现在
dd <- data.frame(
id = 10:13,
text = c("No wonderful, then, that ever",
"So that in many cases such a ",
"But there were still other and",
"Not even at the rationale")
, stringsAsFactors = F
)
,为了从data.frame读取特殊的属性,我们将使用readTabular
功能,使我们自己的自定义data.frame读者
library(tm)
myReader <- readTabular(mapping = list(content = "text", id = "id"))
指定用于data.frame中的内容和id的列。现在我们用DataframeSource
读取它,但使用我们的自定义阅读器。
tm <- VCorpus(DataframeSource(dd), readerControl = list(reader = myReader))
现在,如果我们只想保留一定的单词集,我们可以创建自己的content_transformer函数。一种方法是
keepOnlyWords <- content_transformer(function(x, words) {
regmatches(x,
gregexpr(paste0("\\b(", paste(words, collapse = "|"), "\\b)"), x)
, invert = T) <- " "
x
})
这将用空格替换不在单词列表中的所有内容。请注意,您可能希望在此之后运行stripWhitespace
。因此,我们的转换看起来就像
keep <- c("wonder", "then", "that", "the")
tm <- tm_map(tm, content_transformer(tolower))
tm <- tm_map(tm, keepOnlyWords, keep)
tm <- tm_map(tm, stripWhitespace)
检查DTM矩阵:
> inspect(dtm)
<<DocumentTermMatrix (documents: 4, terms: 4)>>
Non-/sparse entries: 7/9
Sparsity : 56%
Maximal term length: 6
Weighting : term frequency (tf)
Terms
Docs ratio that the wonder
10 0 1 1 1
11 0 1 0 0
12 0 0 1 0
13 1 0 1 0
谢谢你的详细解答。很棒! @alistaire – BEMR