使用 tm 函数时保留唯一标识符(例如,记录 ID)- 不适用于大量数据?

Retaining unique identifiers (e.g., record id) when using tm functions - doesn't work with lot's of data?

我正在处理非结构化文本 (Facebook) 数据,并且正在对其进行预处理(例如,去除标点符号、删除停用词、词干提取)。我需要在预处理时保留记录(即 Facebook post)的 ID。我有一个适用于数据子集但对所有数据都失败的解决方案 (N = 127K posts)。我试过对数据进行分块,但这也不起作用。我认为这与我使用变通方法并依赖行名有关。例如,它似乎适用于前 ~15K posts 但是当我继续子集化时,它失败了。我意识到我的代码不够优雅,所以很高兴学习 better/completely 不同的解决方案——我所关心的只是在我转到 V Corpus 并再次返回时保留 ID。我是 tm 包的新手,尤其是 readTabular 函数。 (注意:我 运行 在制作 VCorpus 之前降低和删除单词,因为我最初认为这是问题的一部分)。

工作代码如下:

示例数据

fb = data.frame(RecordContent = c("I'm dating a celebrity! Skip to 2:02 if you, like me, don't care about the game.",
                                "Photo fails of this morning. Really Joe?", 
                                "This piece has been almost two years in the making. Finally finished! I'm antsy for October to come around... >:)"),
                                FromRecordId = c(682245468452447, 737891849554475, 453178808037464),
                                stringsAsFactors = F)

删除标点符号并改为小写

fb$RC = tolower(gsub("[[:punct:]]", "", fb$RecordContent)) 
fb$RC2 = removeWords(fb$RC, stopwords("english"))

第 1 步:创建特殊的 reader 函数来保留记录 ID

myReader = readTabular(mapping=list(content="RC2", id="FromRecordId"))

第 2 步:制作我的语料库。使用 DataframeSource 和自定义 reader 函数读取数据,其中每个 FB post 是一个 "document"

corpus.test = VCorpus(DataframeSource(fb),      readerControl=list(reader=myReader))

第 3 步:清洁和干

 corpus.test2 = corpus.test %>% 
tm_map(removeNumbers) %>% 
tm_map(stripWhitespace) %>% 
tm_map(stemDocument, language = "english") %>% 
as.VCorpus()

第四步:将语料库做回字符向量。行名现在是 ID

fb2 = data.frame(unlist(sapply(corpus.test2, `[`, "content")), stringsAsFactors = F)

第 5 步:为以后的合并创建新的 ID 变量,命名变量,并准备合并回原始数据集

fb2$ID = row.names(fb2)
fb2$RC.ID = gsub(".content", "", fb2$ID)
colnames(fb2)[1] = "RC.stem"
fb3 = select(fb2, RC.ID, RC.stem)
row.names(fb3) = NULL

我认为 ID 默认情况下由 tm 模块存储和保留的。您可以使用

全部获取它们(以矢量化方式)

meta(corpus.test, "id")

$`682245468452447`
[1] "682245468452447"

$`737891849554475`
[1] "737891849554475"

$`453178808037464`
[1] "453178808037464"

我建议阅读 tm::meta() 函数的文档,但不是很好。

您还可以 添加 任意元数据(作为键值对)到语料库中的每个集合项,以及集合级元数据。