根据文本文件

时间:2016-03-24 12:37:10

标签: r tm corpus

我正在使用R和tm包进行一些文本分析。 我正在尝试根据是否在单个文本文件的内容中找到某个表达式来构建语料库的子集。

我创建了一个包含20个文本文件的语料库(感谢lukeA这个例子):

reut21578 <- system.file("texts", "crude", package = "tm")
corp <- VCorpus(DirSource(reut21578), list(reader = readReut21578XMLasPlain))

我现在只想选择那些包含字符串“降价”的文本文件来创建子集语料库。

检查文档的第一个文本文件,我知道至少有一个包含该字符串的文本文件:

writeLines(as.character(corp[1]))

我最好怎么做呢?

3 个答案:

答案 0 :(得分:1)

这是使用tm_filter的一种方式:

library(tm)
reut21578 <- system.file("texts", "crude", package = "tm")
corp <- VCorpus(DirSource(reut21578), list(reader = readReut21578XMLasPlain))

( corp_sub <- tm_filter(corp, function(x) any(grep("price reduction", content(x), fixed=TRUE))) )
# <<VCorpus>>
# Metadata:  corpus specific: 0, document level (indexed): 0
# Content:  documents: 1

cat(content(corp_sub[[1]]))
# Diamond Shamrock Corp said that
# effective today it had cut its contract prices for crude oil by
# 1.50 dlrs a barrel.
#     The reduction brings its posted price for West Texas
# Intermediate to 16.00 dlrs a barrel, the copany said.
#     "The price reduction today was made in the light of falling   # <=====
# oil product prices and a weak crude oil market," a company
# spokeswoman said.
#     Diamond is the latest in a line of U.S. oil companies that
# have cut its contract, or posted, prices over the last two days
# citing weak oil markets.
#  Reuter

我是怎么到那儿的?通过查看packages' vignette,搜索子集,然后查看tm_filter(帮助:?tm_filter)的示例,其中提到了这些示例。也许值得查看?grep来检查模式匹配的选项。

答案 1 :(得分:1)

这是使用 quanteda 包的一种更简单的方法,更符合重用已经为其他R对象定义的现有方法的方式。 quanteda 对于语料库对象有一个subset方法,就像data.frame的子集方法一样,但选择逻辑向量,包括语料库中定义的文档变量。下面,我使用语料库对象的texts()方法从语料库中提取文本,并在grep()中使用它来搜索您的单词对。

require(tm)
data(crude)

require(quanteda)
# corpus constructor recognises tm Corpus objects 
(qcorpus <- corpus(crude))
## Corpus consisting of 20 documents.
# use subset method
(qcorpussub <- subset(qcorpus, grepl("price\\s+reduction", texts(qcorpus))))
## Corpus consisting of 1 document.

# see the context
## kwic(qcorpus, "price reduction")
##                       contextPre         keyword             contextPost
## [127, 45:46] copany said." The [ price reduction ] today was made in the

注意:我将正则表达式与“\ s +”隔开,因为您可以使用空格,制表符或换行符的某些变体而不只是单个空格。

答案 2 :(得分:0)

@ lukeA的解决方案有效。我想提供另一种我更喜欢的解决方案。

    library(tm)

        reut21578 <- system.file("texts", "crude", package = "tm")
        corp <- VCorpus(DirSource(reut21578), list(reader = readReut21578XMLasPlain))

        corpTF <- lapply(corp, function(x) any(grep("price reduction", content(x), fixed=TRUE)))

        for(i in 1:length(corp)) 
          corp[[i]]$meta["mySubset"] <- corpTF[i]

        idx <- meta(corp, tag ="mySubset") == 'TRUE'
        filtered <- corp[idx]

        cat(content(filtered[[1]]))

通过使用元标记,此解决方案的优势,我们可以看到所有语料库元素的选择标记 mySubset ,值'TRUE'用于我们选择的标记元素和值< em>'FALSE'否则。