从R中的TM导出语料库

4

我正在尝试将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类型。


1
实际上,在进行词干处理之前,corpora 看起来像是一个 Corpus 类对象,然后在词干处理后它变成了一个 character 类型对象(不能用 writeCorpus 写入)。现在正在研究将其强制转换回 Corpus 对象的方法! - Ben Piché
2
好的,我是一个新手所以无法回答自己的问题,但这就是它:tm将被tm_map调用的Corpus对象转换为character对象。在将它们写入文件系统之前,必须将它们强制转换回Corpus对象,方法是调用 > corpora <- Corpus(VectorSource(corpora)) - Ben Piché
语言:英文至中文将语句翻译为:语料库写入到哪个目录?返回翻译后的文本。 - tumultous_rooster
1个回答

0
我想知道你为什么要导出语料库。如果你想向他人展示文本,可以直接使用原始文本。
如果你想将其导出并在R中重复使用,我的建议是使用函数save()将语料库保存为.RData文件。
然后,如果你想加载它,只需使用load()函数即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接