我有一个包含文档标记的字符向量列表。
list(doc1 = c("I", "like", "apples"), doc2 = c("You", "like", "apples", "too"))
我想将此向量转换为 Quanteda
tokens
(或 dfm
)对象,以便利用一些 Quantedas 功能。
最好的方法是什么?
我意识到我可以对每个文档执行以下操作:
tokens(paste0(c("I", "like", "apples"), collapse = " "), what = "fastestword")
这给出了:
Tokens consisting of 1 document.
text1 :
[1] "I" "like" "apples"
但这感觉像是一种黑客行为,而且也不可靠,因为我的一些令牌对象中有空格。有没有办法可以更顺利地传输这些数据结构?
您可以通过以下方式构造令牌对象:
还可以使用
as.tokens(mylist)
将字符元素列表转换为标记对象。不同之处在于,使用 tokens()
,您可以访问所有选项,例如 remove_punct
。使用as.tokens()
,转换是直接的,没有选项,所以如果你不需要选项会更快一点。
lis <- list(
doc1 = c("I", "like", "apples"),
doc2 = c("One two", "99", "three", ".")
)
library("quanteda")
## Package version: 3.0.9000
## Unicode version: 13.0
## ICU version: 69.1
## Parallel computing: 8 of 8 threads used.
## See https://quanteda.io for tutorials and examples.
tokens(lis)
## Tokens consisting of 2 documents.
## doc1 :
## [1] "I" "like" "apples"
##
## doc2 :
## [1] "One two" "99" "three" "."
tokens(lis, remove_punct = TRUE, remove_numbers = TRUE)
## Tokens consisting of 2 documents.
## doc1 :
## [1] "I" "like" "apples"
##
## doc2 :
## [1] "One two" "three"
强制替代方案,没有选项:
as.tokens(lis)
## Tokens consisting of 2 documents.
## doc1 :
## [1] "I" "like" "apples"
##
## doc2 :
## [1] "One two" "99" "three" "."
根据
?tokens
,x
可以是list
。
x - 标记构造函数的输入对象,其中之一:(唯一)命名的字符列表;令牌对象;或将被标记化的语料库或字符对象
所以我们只需要
library(quanteda)
tokens(lst1, what = 'fastestword')