为什么要重新发明轮子? quanteda 包就是为此而构建的。
定义一个水果向量,作为奖励,我使用(默认)glob 模式匹配类型来捕获单数和复数形式。
A <- c("I have a lot of pineapples, apples and grapes. One day the pineapples person gave the apples person two baskets of grapes")
fruits <- c("apple*", "pineapple*", "grape*", "banana*")
library("quanteda", warn.conflicts = FALSE)
## Package version: 1.4.2
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
然后,一旦您使用 tokens() 将其标记为单词,您就可以使用您的向量 fruits 将结果发送到 tokens_select() 以仅选择这些类型。
toks <- tokens(A) %>%
tokens_select(pattern = fruits)
toks
## tokens from 1 document.
## text1 :
## [1] "pineapples" "apples" "grapes" "pineapples" "apples"
## [6] "grapes"
最后,ntype() 会告诉你单词types(唯一单词)的数量,也就是你想要的输出 3。
ntype(toks)
## text1
## 3
另外,您也可以计算非唯一的出现次数,称为 tokens。
ntoken(toks)
## text1
## 6
这两个函数都被向量化以返回一个命名的整数向量,其中元素名称将是您的文档名称(这里,quanteda 默认为单个文档的“text1”),所以这也很容易工作在大型语料库上高效。
优势? 比正则表达式更容易(并且更易读),而且您可以访问令牌的附加功能。例如,假设您想将单数和复数水果模式视为等价的。您可以在 quanteda 中通过两种方式做到这一点:使用 tokens_replace() 手动将模式替换为规范形式,或者使用 tokens_wordstem() 将水果名称作为词干。
使用tokens_replace():
B <- "one apple, two apples, one grape two grapes, three pineapples."
toksrepl <- tokens(B) %>%
tokens_select(pattern = fruits) %>%
tokens_replace(
pattern = fruits,
replacement = c("apple", "pineapple", "grape", "banana")
)
toksrepl
## tokens from 1 document.
## text1 :
## [1] "apple" "apple" "grape" "grape" "pineapple"
ntype(toksrepl)
## text1
## 3
使用tokens_wordstem():
toksstem <- tokens(B) %>%
tokens_select(pattern = fruits) %>%
tokens_wordstem()
toksstem
## tokens from 1 document.
## text1 :
## [1] "appl" "appl" "grape" "grape" "pineappl"
ntype(toksstem)
## text1
## 3