一些整理文本的帮助

问题描述 投票:1回答:1

我有一个正在使用tidytext处理的项目,这是我的新手。我的输入数据当前为文件夹中单个.txt文件的形式。我成功地使用get_sentiments()来跟踪数据的积极/消极情绪,但我希望进行一些更高级的主题建模。

https://www.tidytextmining.com/topicmodeling.html#latent-dirichlet-allocation

我正在尝试根据本指南进行操作,但是我正在努力入门。看起来您需要进行主题建模的输入数据是DocumentTermMatrix,我不确定该如何创建。有没有办法将当前作为单个文件保存的数据转换为这种格式,以便我可以使用该指南中介绍的方法?

r text-mining topic-modeling tidytext
1个回答
2
投票

您可以将所有.txt文件读入df并使用tm在其中创建一个DocumentTermMatrix:

library(tidyverse)
library(readtext)
library(tm)

# make example text files
text1 <- c("hello world 77")
text2 <- c("What time is it? 23")

writeLines(text1,"./data/text1.txt")
writeLines(text2,"./data/text2.txt")

# read txt files
texts <- list.files("./data",full.names = TRUE) # you can replace this path with your folder path with the text files
readtext(texts) -> data

# transform the data to a corpus
Corpus(VectorSource(data$text)) -> corpus

# add normalizations (you can skip this or add more)
corpus = tm_map(corpus, content_transformer(tolower))
corpus = tm_map(corpus, removeNumbers)

# make document-term matix
review_dtm <- DocumentTermMatrix(corpus)

review_dtm
<<DocumentTermMatrix (documents: 2, terms: 5)>>
Non-/sparse entries: 5/5
Sparsity           : 50%
Maximal term length: 5
Weighting          : term frequency (tf)
© www.soinside.com 2019 - 2024. All rights reserved.