【问题标题】:Is there any way to split quanteda tokens into n equal parts?有没有办法将 quanteda 令牌分成 n 个相等的部分?
【发布时间】:2020-11-24 15:41:05
【问题描述】:

我正在使用 R 中的 quanteda 包执行文本分析。

我有一组已经标记化的文本文档。每个都包含不同数量的代币。我想将标记分成 N 个相等的标记块(例如,10 或 20 个块,每个文本包含相同数量的标记)。

假设我的数据名为text_docs,如下所示:

Text  | Tokens
Text1 | "this" "is" "an" "example" "this" "is" "an" "example"
Text2 | "this" "is" "an" "example"
Text3 | "this" "is" "an" "example" "this" "is" "an" "example" "this" "is" "an" "example"

我想要得到的结果应该是这样的(两块而不是二十块):

Text  | Chunk1                                 | Chunk2
Text1 | "this" "is" "an" "example"             | "this" "is" "an" "example"
Text2 | "this" "is"                            | "an" "example"
Text3 | "this" "is" "an" "example" "this" "is" | "an" "example" "this" "is" "an" "example"

我知道quanteda 中的tokens_chunk 函数。然而,这个功能只能让我创建一组大小相等的块(例如,每个块由两个标记组成),这给我留下了不同数量的块。此外,tokens_chunk 函数中的命令size 必须是单个整数,这就是为什么我不能简单地这样做chunks <- tokens_chunk(text_docs, size = ntokens(text_docs)/20)

有什么想法吗?

提前谢谢你。

【问题讨论】:

  • 你想要什么对象类作为你的输出?您显示的不是 R 对象,而是表格。令牌对象没有分区,所以你想要 Text1.1、Text1.2、Text 2.1 等还是其他一些基本 R 对象适合你?
  • 很抱歉显示“非 R”输出。由于这是我在 stackoverflow 上的第一篇文章,我不确定如何显示所需的输出。如果输出是 Text1.1、Text1.2 等等,那就太好了,因为我的下一步是创建一个文档术语矩阵。但是,如果更容易创建,我也可以使用类似 data.frame 的东西。

标签: r nlp quanteda


【解决方案1】:
library("quanteda")
## Package version: 2.1.2

toks <- c(
  Text1 = "this is an example this is an example",
  Text2 = "this is an example",
  Text3 = "this is an example this is an example this is an example"
) %>%
  tokens()

toks
## Tokens consisting of 3 documents.
## Text1 :
## [1] "this"    "is"      "an"      "example" "this"    "is"      "an"     
## [8] "example"
## 
## Text2 :
## [1] "this"    "is"      "an"      "example"
## 
## Text3 :
##  [1] "this"    "is"      "an"      "example" "this"    "is"      "an"     
##  [8] "example" "this"    "is"      "an"      "example"

这是做你想做的事的一种方法。我们将覆盖文档名称以切出每个文档,然后使用大小等于其长度一半的tokens_chunk() 将其拆分。在这里,我还使用了ceiling,这样如果文档的令牌长度是奇数,那么它在第一次拆分时会比第二次拆分多一个。 (您的示例都是针对偶数标记的文档,但这也处理奇数标记的情况。)

lis <- lapply(
  docnames(toks),
  function(x) tokens_chunk(toks[x], size = ceiling(ntoken(toks[x]) / 2))
)

这会产生一个拆分标记列表,您可以使用连接标记的c() 函数重新组合它们。您可以使用 do.call() 将其应用于列表。

do.call("c", lis)
## Tokens consisting of 6 documents.
## Text1.1 :
## [1] "this"    "is"      "an"      "example"
## 
## Text1.2 :
## [1] "this"    "is"      "an"      "example"
## 
## Text2.1 :
## [1] "this" "is"  
## 
## Text2.2 :
## [1] "an"      "example"
## 
## Text3.1 :
## [1] "this"    "is"      "an"      "example" "this"    "is"     
## 
## Text3.2 :
## [1] "an"      "example" "this"    "is"      "an"      "example"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2021-09-29
    • 2023-03-25
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多