繁体   English   中英

如何在语料库文档中添加单词?

[英]how to add words into documents in corpus?

我正在使用tm软件包在我的语料库上运行LDA。 我的语料库包含10,000个文档。

rtcorpus.4star <- Corpus(DataframeSource(rt.subset.4star)) ##creates the corpus
rtcorpus.4star[[1]] ##accesses the first document

我正在尝试编写一段代码,在某些单词之后添加“ specialword”一词。 本质上就是这样:对于我选择的单词向量(好,高兴,快乐,有趣,爱),我想让代码遍历每个文档,并在这些单词中的任何一个后面添加单词“ specialword”。

因此,例如,给定此文档:

I had a really fun time

我希望结果是这样的:

I had a really fun specialword time

问题是我不确定如何执行此操作,因为我不知道如何在语料库中读取代码。 我知道我应该进行for循环(或可能不这样做),但是我不确定如何循环遍历每个文档中的每个单词以及语料库中的每个文档。 我也想知道是否可以在tm_map中使用“ translate”函数的形式。


编辑::

做了一些尝试。 此代码将“ test”返回为NA。 你知道为什么吗?

special <- c("poor", "lose")
for (i in special){
test <- gsub(special[i], paste(special[i], "specialword"), rtcorpus.1star[[1]])
}

编辑:想通了! 谢谢

special <- c("poor", "lose")
for (i in 1:length(special)){
rtcorpus.codewordtest <-gsub(special[i], paste(special[i], "specialword"), rtcorpus.codewordtest)
}

如果您尝试这样的事情怎么办?

corpus <- read("filename.txt")
special <- c("fun","nice","love")
for (w in special) {
    gsub(w, w + " specialword", corpus)}

这将加载文件,遍历单词列表,并将单词替换为单词本身,后跟“ specialword”(注意空格)。

编辑:我刚刚看到您有多个文件。 要遍历语料库中的文件,可以执行以下操作:

 corpus <- "filepath/desktop/wherever/folderwithcorpus/"
 special <- c("fun","nice","love")

 for (file in corpus){
      data <- read(file)
      for (w in special){
           gsub(w, w + " specialword", corpus)}
      }

也许这不是tm软件包的功能,但是您可以对某些单词的向量执行简单的paste()函数,然后在其后立即添加“ specialword”。 或者如果您的文档可以在列表中(我认为),则stringr包中的str_replace()会执行此操作。

然后创建语料库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM