在R tm中添加自定义停止语



我在R中有一个使用tm包的语料库。我正在应用removeWords函数来删除停止字

tm_map(abs, removeWords, stopwords("english")) 

有没有办法将我自己的自定义停止词添加到此列表中?

stopwords只是为您提供了一个单词向量,而c则将您自己的单词与之相结合。

tm_map(abs, removeWords, c(stopwords("english"),"my","custom","words")) 

将自定义stop words保存在csv文件中(例如:word.csv)。

library(tm)
stopwords <- read.csv("word.csv", header = FALSE)
stopwords <- as.character(stopwords$V1)
stopwords <- c(stopwords, stopwords())

然后可以将custom words应用于文本文件。

text <- VectorSource(text)
text <- VCorpus(text)
text <- tm_map(text, content_transformer(tolower))
text <- tm_map(text, removeWords, stopwords)
text <- tm_map(text, stripWhitespace)
text[[1]]$content

您可以创建一个自定义停止字的矢量&使用这样的语句:

tm_map(abs, removeWords, c(stopwords("english"), myStopWords)) 

您也可以使用textProcessor包。它运行得很好:

textProcessor(documents, 
  removestopwords = TRUE, customstopwords = NULL)

可以将您自己的停止字添加到tm安装附带的默认停止字列表中。"tm"软件包附带了许多数据文件,包括stopwords,请注意stopwwords文件适用于多种语言。您可以在stopwords目录下添加、删除或更新english.dat文件
找到stopwords目录的最简单方法是通过文件浏览器在系统中搜索"stopwordes"目录。你应该可以找到english.dat以及许多其他语言文件。从RStudio打开english.dat文件,该文件应能够编辑文件-您可以根据需要添加自己的单词或删除现有单词。如果你想用任何其他语言编辑停止语,这是一个相同的过程。

我使用的是stopwwords库,而不是tm库。我只是决定把我的解决方案放在这里,以防有人需要。

# Create a list of custom stopwords that should be added
word <- c("quick", "recovery")
lexicon <-  rep("custom", times=length(word))
# Create a dataframe from the two vectors above
mystopwords <- data.frame(word, lexicon)
names(mystopwords) <- c("word", "lexicon")
# Add the dataframe to stop_words df that exists in the library stopwords
stop_words <-  dplyr::bind_rows(stop_words, mystopwords)
View(stop_words)

最新更新