使用gsub函数通过读取.csv文件替换单词 setwd(“C:\\Users\\Joshua\\Documents\\TextMining\\Description\u text”) 库(RTextTools) 库(topicmodels) 图书馆(tm) 图书馆(SnowballC) #扣押 #cnamePS=file.path(“C:\\Users\\Joshua\\Documents\\TextMining\”) cnamePS=file.path(“C:\\Users\\Joshua\\Documents\\TextMining\\Description\u text”) docs

使用gsub函数通过读取.csv文件替换单词 setwd(“C:\\Users\\Joshua\\Documents\\TextMining\\Description\u text”) 库(RTextTools) 库(topicmodels) 图书馆(tm) 图书馆(SnowballC) #扣押 #cnamePS=file.path(“C:\\Users\\Joshua\\Documents\\TextMining\”) cnamePS=file.path(“C:\\Users\\Joshua\\Documents\\TextMining\\Description\u text”) docs,r,replace,gsub,R,Replace,Gsub,证明我的.csv文件有问题 我在单词之间漏掉了一个逗号 这是一个很好的提醒,最小的事情都可能导致整个代码无法运行。在运行此代码之前,请尝试options(error=recover)。这将在出现错误时启动调试器,您可以看到replacementtable$phrase[r]的外观。我认为可能是数据中存在一些保留的元字符导致了这种情况,例如,存在“(”或“+”或“*”etc具有特殊意义,如果您的数据包含这些符号,则会发生此错误,除非这些符号用“\\”转义。感谢您的查看。我已经启动了调试器并发布了我

证明我的.csv文件有问题

我在单词之间漏掉了一个逗号


这是一个很好的提醒,最小的事情都可能导致整个代码无法运行。

在运行此代码之前,请尝试
options(error=recover)
。这将在出现错误时启动调试器,您可以看到
replacementtable$phrase[r]
的外观。我认为可能是数据中存在一些保留的元字符导致了这种情况,例如,存在“(”或“+”或“*”etc具有特殊意义,如果您的数据包含这些符号,则会发生此错误,除非这些符号用“\\”转义。感谢您的查看。我已经启动了调试器并发布了我所看到的内容。什么是“\\”对不起。
setwd("C:\\Users\\Joshua\\Documents\\TextMining\\Description_text")
library(RTextTools)
library(topicmodels)
library(tm)
library(SnowballC)

#Seizure
#cnamePS=file.path("C:\\Users\\Joshua\\Documents\\TextMining\\")
cnamePS=file.path("C:\\Users\\Joshua\\Documents\\TextMining\\Description_text")
docs <- Corpus(DirSource(cnamePS), readerControl=list(reader=readPlain))

#clean file
docsA <- tm_map(docs, removePunctuation)
docsA <- tm_map(docsA, removeNumbers)

docsA=tm_map(docsA,content_transformer(tolower))
docsA=tm_map(docsA,removeWords,stopwords("english"))

#phrase replacement
phrasesReplacement <- read.csv("C:\\Users\\Joshua\\Documents\\TextMining\\phrases.csv", stringsAsFactors = FALSE)
replacePhrasesFunc <- function(txt, replacementtable)
{

  txt<-gsub("-","",txt)

  for (r in seq(nrow(replacementtable)))
  {
    txt <- gsub(replacementtable$phrase[r], replacementtable$replacement[r], txt, fixed=TRUE)
  }
  return(txt)
}

replacePhrases <- content_transformer(replacePhrasesFunc)

docsA <- tm_map(docsA, replacePhrases, phrasesReplacement)#keep phrase


#docsAcopy=docsA #make copy

#docsA=tm_map(docsA,stemDocument) 

docsA=tm_map(docsA,stripWhitespace)
> docsA <- tm_map(docsA, replacePhrases, phrasesReplacement)#keep phrase
Error in gsub(replacementtable$phrase[r], replacementtable$replacement[r],  : 
  invalid 'pattern' argument
Called from: gsub(replacementtable$phrase[r], replacementtable$replacement[r], 
    txt, fixed = TRUE)