首页 > 解决方案 > 在 Quanteda 中构建语料库,同时跟踪 ID

问题描述

我有一个数据集,其中每个用户有多个文本。我想用 Quanteda 构建所有这些文档的语料库,但又不会失去将不同文本链接回相应用户的能力。

我会给你一个示例代码来帮助你更多地理解我失败的地方。

df <- data.frame('ID'=c(1,1,2), 'Text'=c('I ate apple', "I don't like fruits", "I swim in the dark"), stringsAsFactors = FALSE)
df_corpus <- corpus(df$Text, docnames =df$ID)
corpus_DFM <- dfm(df_corpus, tolower = TRUE, stem = FALSE)
print(corpus_DFM)

这导致

Document-feature matrix of: 3 documents, 10 features (60.0% sparse).
3 x 10 sparse Matrix of class "dfm"
     features
docs  i ate apple don't like fruits swim in the dark
  1   1   1     1     0    0      0    0  0   0    0
  1.1 1   0     0     1    1      1    0  0   0    0
  2   1   0     0     0    0      0    1  1   1    1
> 

但我想在我的文档特征矩阵中获得这样的数据框


Document-feature matrix of: 3 documents, 10 features (60.0% sparse).
3 x 10 sparse Matrix of class "dfm"
       features
docs    id  i ate apple don't like fruits swim in the dark
  text1 1   1   1     1     0    0      0    0  0   0    0
  text2 1   1   0     0     1    1      1    0  0   0    0
  text3 2   1   0     0     0    0      0    1  1   1    1
> 

有没有办法使用 Quanteda 自动化这个过程。我想修改 dfm 对象的 docs 列,但我不知道如何访问它。

欢迎任何帮助!

谢谢你。

标签: rnlpquanteda

解决方案


这里的问题是您将文档名称指定为“ID”,但文档名称必须是唯一的。这就是语料库构造函数根据非唯一 ID 为您的文档名分配 1、1.1、2 的原因。

解决方案?让我们corpus()分配文档名,并保留ID为 docvar(文档变量)。通过将 data.frame 输入到 最容易做到这一点corpus(),它调用 data.frame 方法而不是 character 方法corpus()。(见?语料库。)

将您的代码更改为:

> df_corpus <- corpus(df, text_field =  "Text")
> corpus_DFM <- dfm(df_corpus, tolower = TRUE, stem = FALSE)
> print(corpus_DFM)
Document-feature matrix of: 3 documents, 10 features (60.0% sparse).
3 x 10 sparse Matrix of class "dfm"
       features
docs    i ate apple don't like fruits swim in the dark
  text1 1   1     1     0    0      0    0  0   0    0
  text2 1   0     0     1    1      1    0  0   0    0
  text3 1   0     0     0    0      0    1  1   1    1
> 
> docvars(corpus_DFM, "ID")
[1] 1 1 2

如果您愿意,这使您可以轻松地按用户重新组合您的 dfm:

> dfm_group(corpus_DFM, groups = "ID")
Document-feature matrix of: 2 documents, 10 features (45.0% sparse).
2 x 10 sparse Matrix of class "dfm"
    features
docs i ate apple don't like fruits swim in the dark
   1 2   1     1     1    1      1    0  0   0    0
   2 1   0     0     0    0      0    1  1   1    1

推荐阅读