r - 在 R 中形成没有停用词的二元组

标签 r text-mining tm n-gram quanteda

我最近在使用 R 进行文本挖掘时遇到了一些问题。 目的是找到新闻中有意义的关键词,例如“智能汽车”和“数据挖掘”。

假设我有一个如下字符串:

"IBM have a great success in the computer industry for the past decades..."

删除停用词后(“have”、“a”、“in”、“the”、“for”),

"IBM great success computer industry past decades..."

最终,会出现“成功计算机”或“行业过去”等二元组。

但我真正需要的是两个单词之间不存在停用词,例如“computer Industry”是我想要的二元组的明显示例。

我的代码部分如下:

corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, stripWhitespace) 
corpus <- tm_map(corpus, stemDocument)
NgramTokenizer = function(x) {unlist(lapply(ngrams(words(x), 2), paste, collapse = " "), use.names = FALSE)}
dtm <- TermDocumentMatrix(corpus, control = list(tokenize = NgramTokenizer))

有什么方法可以避免在计算TF时出现“成功计算机”之类的结果吗?

最佳答案

注意:于 2017 年 10 月 12 日进行编辑以反射(reflect)新的 Quanteda 语法。

您可以在 quanteda 中执行此操作,它可以在 ngram 形成后从它们中删除停用词。

txt <- "IBM have a great success in the computer industry for the past decades..."

library("quanteda")
myDfm <- tokens(txt) %>%
    tokens_remove("\\p{P}", valuetype = "regex", padding = TRUE) %>%
    tokens_remove(stopwords("english"), padding  = TRUE) %>%
    tokens_ngrams(n = 2) %>%
    dfm()

featnames(myDfm)
# [1] "great_success"     "computer_industry" "past_decades" 

它的作用:

  1. 表单 token 。
  2. 使用正则表达式删除标点符号,但在删除的位置留下空格。这可以确保您不会使用从一开始就不相邻的标记来形成 ngram,因为它们是用标点符号分隔的。
  3. 删除停用词,同时将 pad 保留在原位。
  4. 形成二元组。
  5. 构造文档特征矩阵。

要获取这些二元组的计数,您可以直接检查 dfm,或使用 topfeatures():

myDfm
# Document-feature matrix of: 1 document, 3 features.
# 1 x 3 sparse Matrix of class "dfmSparse"
#        features
# docs    great_success computer_industry past_decades
#   text1             1                 1            1

topfeatures(myDfm)
#    great_success computer_industry      past_decades 
#                1                 1                 1 

关于r - 在 R 中形成没有停用词的二元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34282370/

相关文章:

text-processing - 术语聚类库?

r - vline左侧的阴影密度图?

css - 如何将多个样式表附加到 rmarkdown 文档?

r - 访问r中工作目录中不同文件夹中的数据

r - 删除具有重复值的行并将 NA 作为单独的值包含在内

python - 斯坦福西类牙语 POS Tagger 标签的含义

python - python luigi意外退出,退出代码为-11

R:为wordcloud图形/png添加标题

r - 在Mac上的R 3.0.1中,tm_map具有parallel::mclapply错误

r - 如何制作 1 亿条推文的 R tm 语料库?