如何将字符向量列表转换为Quanteda tokens对象?

问题描述 投票:0回答:2

我有一个包含文档标记的字符向量列表。

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"

但这感觉像是一种黑客行为,而且也不可靠,因为我的一些令牌对象中有空格。有没有办法可以更顺利地传输这些数据结构?

r quanteda
2个回答
2
投票

您可以通过以下方式构造令牌对象:

  • 一个字符向量,在这种情况下,对象被标记化,每个字符元素成为一个“文档”
  • 语料库,它是一种特殊分类的字符向量,并以相同的方式被标记化并转换为标记对象中的文档
  • 字符元素列表,在这种情况下,每个列表元素都成为标记化文档,并且该列表的每个元素都成为标记(但不会进一步标记化)
  • 一个标记对象,其处理方式与字符元素列表相同。

还可以使用

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"   "."

0
投票

根据

?tokens
x
可以是
list

x - 标记构造函数的输入对象,其中之一:(唯一)命名的字符列表;令牌对象;或将被标记化的语料库或字符对象

所以我们只需要

library(quanteda)
tokens(lst1, what = 'fastestword')
© www.soinside.com 2019 - 2024. All rights reserved.