我正在尝试将R中的Corpus
对象导出为静态文件。这些语料库包含通过解析文件系统中现有的预处理文件创建的词干文档。作者在他的《R中文本挖掘入门》(第2页)中描述了一种方法来实现这一点,建议:
> writeCorpus(file)
但是,到目前为止,我的尝试只有以下结果:
Error in UseMethod("as.PlainTextDocument", x):
no applicable method for 'as.PlainTextDocument' applied to an object of class "character"
目前我的脚本非常简单,我认为这可能只是一个简单的疏忽。非常感谢您的任何建议:这似乎是个小问题。
# Turn off Java so it doesn't interfere with Weka interface
Sys.setenv(NOAWT=1)
# Load required text mining packages
require(tm)
require(rJava)
require(RWeka)
require(Snowball)
# Populate a vector with the number of subdirectories in preprocessed dir
preprocessed <- list.files(path="preprocessed_dir", include.dirs=TRUE, full.names=TRUE)
# For each element in the vector
for(i in 1:length(preprocessed)) {
# Get the files in each subdirectory by appending a number to the absolute path
files <- list.files(sprintf("preprocessed_dir/%.0f", i))
# Create a Corpus object of all the files in the subdirectory
corpora <- Corpus(VectorSource(files))
# Stem the words in the Corpus object
corpora <- tm_map(corpora, SnowballStemmer)
# (Try to) write the object to the file system
writeCorpus(corpora)
}
FWIW:调用class(corpora)
会返回[1] "VCorpus" "Corpus" "list"
,因此这些对象显然不是character
类型。
corpora
看起来像是一个Corpus
类对象,然后在词干处理后它变成了一个character
类型对象(不能用writeCorpus
写入)。现在正在研究将其强制转换回Corpus
对象的方法! - Ben Pichétm
将被tm_map
调用的Corpus
对象转换为character
对象。在将它们写入文件系统之前,必须将它们强制转换回Corpus
对象,方法是调用> corpora <- Corpus(VectorSource(corpora))
。 - Ben Piché