计算R中每行文本数据的ngrams

时间:2013-07-09 18:58:32

标签: r text text-parsing n-gram tm

我有一个以下格式的数据列:

文字

Hello world  
Hello  
How are you today  
I love stackoverflow  
blah blah blahdy  

我想通过使用tau包的textcnt()函数计算此数据集中每行的3克数。但是,当我尝试它时,它给了我一个数字向量,其中包含整个列的ngrams。如何将此功能分别应用于我的数据中的每个观察?

4 个答案:

答案 0 :(得分:6)

这就是你要追求的吗?

library("RWeka")
library("tm")

TrigramTokenizer <- function(x) NGramTokenizer(x, 
                                Weka_control(min = 3, max = 3))
# Using Tyler's method of making the 'Text' object here
tdm <- TermDocumentMatrix(Corpus(VectorSource(Text)), 
                          control = list(tokenize = TrigramTokenizer))

inspect(tdm)

A term-document matrix (4 terms, 5 documents)

Non-/sparse entries: 4/16
Sparsity           : 80%
Maximal term length: 20 
Weighting          : term frequency (tf)

                      Docs
Terms                  1 2 3 4 5
  are you today        0 0 1 0 0
  blah blah blahdy     0 0 0 0 1
  how are you          0 0 1 0 0
  i love stackoverflow 0 0 0 1 0

答案 1 :(得分:4)

这是使用qdap package

的ngram方法
## Text <- readLines(n=5)
## Hello world
## Hello
## How are you today
## I love stackoverflow
## blah blah blahdy

library(qdap)
ngrams(Text, seq_along(Text), 3)

这是一个列表,您可以使用典型的列表索引访问组件。

修改

就你的第一种方法而言,尝试这样:

library(tau)
sapply(Text, textcnt, method = "ngram")

## sapply(eta_dedup$title, textcnt, method = "ngram")

答案 2 :(得分:3)

以下是使用quanteda包的方法:

txt <- c("Hello world", "Hello", "How are you today", "I love stackoverflow", "blah blah blahdy")

require(quanteda)
dfm(txt, ngrams = 3, concatenator = " ", verbose = FALSE)
## Document-feature matrix of: 5 documents, 4 features.
## 5 x 4 sparse Matrix of class "dfmSparse"
##   features
## docs    how are you are you today i love stackoverflow blah blah blahdy
##  text1           0             0                    0                0
##  text2           0             0                    0                0
##  text3           1             1                    0                0
##  text4           0             0                    1                0
##  text5           0             0                    0                1

答案 3 :(得分:3)

我想OP想要使用tau但是其他人没有使用该包。以下是你在tau中的表现:

data = "Hello world\nHello\nHow are you today\nI love stackoverflow\n  
blah blah blahdy"

bigram_tau <- textcnt(data, n = 2L, method = "string", recursive = TRUE)

这将是一个特里,但您可以将其格式化为具有标记和大小的更经典的数据帧类型:

data.frame(counts = unclass(bigram_tau), size = nchar(names(bigram_tau)))
format(r)

我强烈建议使用tau,因为它可以很好地处理大数据。我用它来创建1 GB的bigrams,它既快速又流畅。