【发布时间】:2017-04-17 12:31:31
【问题描述】:
来自发布的答案:@MrFlick 使用 R 语料库保存文档 ID
我试图稍微修改一个很好的例子。
问题:如何修改 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
【问题讨论】:
标签: r regex text-mining corpus