【问题标题】:Adding custom stopwords in R tm在 R tm 中添加自定义停用词
【发布时间】:2013-08-29 01:51:29
【问题描述】:

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

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

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

【问题讨论】:

    标签: r text-mining stop-words corpus tm


    【解决方案1】:

    stopwords 只是为您提供了一个词向量,只是c将您自己的词组合到这个。

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

    【讨论】:

    • 不必为每个操作都执行此操作,是否有一个文件或字典可以添加这些额外的停用词,例如百分比、美分、百万等?
    【解决方案2】:

    将您的自定义 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
    

    【讨论】:

    • 代码块请使用 4 空格缩进(而不是反引号)
    【解决方案3】:

    您可以创建自定义停用词的向量并使用如下语句:

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

    【讨论】:

    • myStopWords 应该是列表还是字符?你能提供创建 myStopWords 的命令吗?这是否有效 myStopWords
    【解决方案4】:

    您也可以使用textProcessor 包。效果很好:

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

    【讨论】:

    • 如何修改 textProcessor 函数中的停用词?
    【解决方案5】:

    可以将您自己的停用词添加到随 tm install 一起提供的默认停用词列表中。 “tm”包带有许多数据文件,包括停用词,请注意停用词文件适用于多种语言。您可以添加、删除或更新停用词目录下的english.dat 文件。
    查找停用词目录的最简单方法是通过文件浏览器在系统中搜索“停用词”目录。您应该会找到english.dat 以及许多其他语言文件。从 RStudio 打开english.dat 文件,该文件应该可以编辑文件 - 您可以根据需要添加自己的单词或删除现有的单词。 如果您想编辑任何其他语言的停用词,也是同样的过程。

    【讨论】:

      【解决方案6】:

      我使用的是停用词库而不是 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)
      

      【讨论】:

        猜你喜欢
        • 2020-06-30
        • 2015-01-10
        • 2019-12-12
        • 1970-01-01
        • 2020-02-27
        • 2013-08-03
        • 2017-05-01
        • 1970-01-01
        • 2021-10-24
        相关资源
        最近更新 更多