使用特定标记构建Term-Document Matrix(以及所有其他标记)

时间:2014-07-15 23:24:01

标签: r tm

我正在尝试构建一个术语 - 文档矩阵,列出语料库中的所有unigrams,但也提取了一个特定的bigrams列表。因此,例如在句子中,“使用你的转向信号”它将列出“使用”,“你的”和“转向信号”。

在文档中,他们提供的示例标记生成器是:

strsplit_space_tokenizer <- function(x) unlist(strsplit(as.character(x), "[[:space:]]+"))

关于如何编写一个标记器来查找给定的双字母向量并将其余部分作为unigrams返回的任何想法?

谢谢!

2 个答案:

答案 0 :(得分:1)

这是一种可能的策略。基本上你可以传递文本,找到你的双字母并用不会在空格上分割的东西替换它们(这里我使用“{0}”,其中实际数字是列表中的二元组的索引)。然后我拆分字符串,然后我通过并用bigram值替换“{0}”值。例如,这里有一个函数,它将构建一个带有bigrams列表的tokenizer

getBigramTokenizer <- function(bigrams=character(0)) {
    force(bigrams)
    return(function(x) {
        x <- Reduce(function(a,b) 
            gsub(bigrams[b],paste0("{",b,"}"),a, fixed=T), 
            seq_along(bigrams), x)
        x <- unlist(strsplit(as.character(x), "[[:space:]]+"))
        m<-regexec("\\{(\\d+)\\}", x)
        i<-which(sapply(m, '[', 1) != -1)
        mi<-sapply(regmatches(x,m)[i], '[', 2)
        x[i]<-bigrams[as.numeric(mi)]
        x
     })
}

现在我们可以将它与

一起使用
bigrams <- c("turn signal", "back seat", "buckle up")
tk <- getBigramTokenizer(bigrams)

tk("use your turn signal")
# [1] "use"         "your"        "turn signal"

tk("please buckle up in the back seat")
# [1] "please"    "buckle up" "in"        "the"       "back seat"

答案 1 :(得分:0)

如果我理解正确,那么qdap版本2.1.1也可以在这里提供帮助:

library(tm)
library(qdap)

## the bigrams
bigrams <- c("turn signal", "back seat", "buckle up")

## fake data (MWE)
dat <- data.frame(docs=paste0("doc", 1:5), 
    state=c("use your turn signal",
        "please buckle up in the back seat",
        "buckle up for safety",
        "Sit in the back seat",
        "here it is"
    )
)

## make data into a Corpus
myCorp <- as.Corpus(dat$state, dat$docs)

myDF <- as.data.frame(myCorp)
f <- sub_holder(bigrams, myDF$text)
tdm <- as.tdm(f$output, myDF$docs)
rownames(tdm) <- f$unhold(rownames(tdm))
inspect(tdm)

##              Docs
## Terms         doc1 doc2 doc3 doc4 doc5
##   for            0    0    1    0    0
##   here           0    0    0    0    1
##   in             0    1    0    1    0
##   is             0    0    0    0    1
##   it             0    0    0    0    1
##   please         0    1    0    0    0
##   turn signal    1    0    0    0    0
##   back seat      0    1    0    1    0
##   buckle up      0    1    1    0    0
##   safety         0    0    1    0    0
##   sit            0    0    0    1    0
##   the            0    1    0    1    0
##   use            1    0    0    0    0
##   your           1    0    0    0    0