【问题标题】:How can I manually set the document id in a corpus?如何在语料库中手动设置文档 ID?
【发布时间】:2016-03-23 18:26:44
【问题描述】:

我正在从数据框创建一个 Copus。我将它作为VectorSource 传递,因为我只想将一列用作文本源。这项工作发现但是我需要语料库中的文档 ID 来匹配数据框中的文档 ID。文档 ID 存储在原始数据框中的单独列中。

df <- as.data.frame(t(rbind(c(1,3,5,7,8,10), 
                        c("text", "lots of text", "too much text", "where will it end",         "give peas a chance","help"))))
colnames(df) <- c("ids","textColumn")
library("tm")
library("lsa")
corpus <- Corpus(VectorSource(df[["textColumn"]]))

运行此代码会创建一个语料库,但文档 ID 的范围是 1-6。有什么方法可以创建文档 ID 为 1、3、5、7、8、10 的语料库?

【问题讨论】:

    标签: r tm


    【解决方案1】:

    我知道@user1098798 可能已经晚了,但是有一种方法可以在创建语料库时直接指定 ID。您需要将数据加载为DataframeSource() 并将映射添加到列:

    corpus = VCorpus(DataframeSource(df), readerControl = list(reader = readTabular(mapping = list(content = "textColumn", id = "ids"))))
    

    【讨论】:

      【解决方案2】:

      好吧,一种简单但不是很优雅的方式来将您的 id 分配给您的文档,可能如下:

      for (i in 1:length(corpus)) {
         attr(corpus[[i]], "ID") <- df$ids[i]
      }
      

      【讨论】:

      • 有效!我会稍等一下,看看是否有人能想出更优雅的东西,也许在实际的语料库创建过程中分配它们。但如果他们不能,我很乐意接受这一点,如果不是为了你的回答速度;)
      • @user1098798 谢谢!我稍微修改了我的答案,因为显然您可以直接重用原始数据中的 id...
      【解决方案3】:

      这里有一个解决这个问题的 qdap 方法,可以在没有循环的情况下处理它:

      从一开始就使用qdap version >= 1.1.0 将数据帧转换为Corpus,ID 标签将被自动添加。

      with(df, as.Corpus(textColumn, ids))
      
      ## <<VCorpus>>
      ## Metadata:  corpus specific: 0, document level (indexed): 3
      ## Content:  documents: 6
      
      
      ## Look around a bit
      meta(with(df, as.Corpus(textColumn, ids)), tag="id")
      inspect(with(df, as.Corpus(textColumn, ids)))
      

      【讨论】:

      • df2tm_corpus 已弃用;你可以编辑你的答案并用as.Corpus代替吗?
      • 这不起作用!,我的结果中总是有空值
      猜你喜欢
      • 1970-01-01
      • 2019-02-13
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      相关资源
      最近更新 更多