首页 > 解决方案 > 从R中的字符串创建词袋

问题描述

我找到了许多词袋的实现,但仍然找不到简单的长字符串的简单实现。我的结果是这样的:

word1:     56
word2:     31
word:X     7

我的库有问题,qdap因为 in 在我的 R 上不起作用...

标签: rtexttext-mining

解决方案


由于大小写和标点符号,使用类似的东西strsplit可能不会完全符合您的要求。包tokenizerstidytext.

library(tokenizers)

text <- "this is some random TEXT is string 45 things and numbers and text!"

table(tokenize_words(text))

     45     and      is numbers  random    some  string    text  things    this 
      1       2       2       1       1       1       1       2       1       1 

如果您只是按空格分割,请注意差异。

table(strsplit(text, " "))

     45     and      is numbers  random    some  string    TEXT   text!  things    this 
      1       2       2       1       1       1       1       1       1       1       1

如果你走这条路,你可能只想完全跳到tidytext.

library(dplyr)
library(tidytext)
library(tibble)

df <- tibble(string = text)

df %>%
  unnest_tokens(word, string) %>%
  count(word)

# A tibble: 10 x 2
   word        n
   <chr>   <int>
 1 45          1
 2 and         2
 3 is          2
 4 numbers     1
 5 random      1
 6 some        1
 7 string      1
 8 text        2
 9 things      1
10 this        1

推荐阅读