【问题标题】:How do I search the number of occurrences of individual words in text data?如何搜索文本数据中单个单词的出现次数?
【发布时间】:2017-08-17 17:01:43
【问题描述】:

如何找到单词列表的出现次数?我可以搜索一个词如下:

dplyr::filter(data, grepl("apple", data$content,ignore.case = TRUE))
length(x$content)

|separator 允许我总结所有出现的情况。但我想单独计算每个单词。

单词可以在 csv 中作为一行提供,也可以在 R 本身中作为向量写入,例如:

words <- c("apple","orange","pear","pineapple")

一个问题是data$count 是一列推文,因此该词在每条推文中可能出现多次。所以我只想计算它们是否出现在行中。

【问题讨论】:

  • stringr::str_count

标签: r loops apply


【解决方案1】:

您可以获得logical 值来表示您的目标词的存在/不存在,如下所示:

library(tidyverse)

words <- c("apple","orange","pear","pineapple")

data <- tibble(content = c("Ony my grocery list are green apples, red apples and oranges",
                           "My favorite froyo flavors are pineapple, peach-pear and pear"))

boundary_words <- paste0("\\b", words) # if you want to avoid counting the apple in pineapple

map_dfc(boundary_words, ~ as.tibble(grepl(., data$content))) %>%
    set_names(words) %>%
    bind_cols(data, .)

# A tibble: 2 x 5
                                                       content apple orange  pear pineapple
                                                         <chr> <lgl>  <lgl> <lgl>     <lgl>
1 Ony my grocery list are green apples, red apples and oranges  TRUE   TRUE FALSE     FALSE
2 My favorite froyo flavors are pineapple, peach-pear and pear FALSE  FALSE  TRUE      TRUE

【讨论】:

  • 太好了,谢谢。我添加的一个扩展是将对象命名为 newdata 并用 apply(X=newdata[9:12],2,FUN=function(x) length(which(x=='TRUE'))) 计算相关列中“TRUE”的数量
【解决方案2】:

使用stringr 包...

library(stringr)
words <- c("apple","orange","pear","pineapple")

data <- c("On my grocery list are green apples, red apples and oranges",
          "Oranges are my favourite, but I also like pineapples and pearls")

sapply(words,function(w) 
       str_count(str_to_lower(str_split(data," ")), #split into words and set to lower case
                 paste0("\\b",w,"s*\\b"))) #adds word boundaries and optional plural -s

     apple orange pear pineapple
[1,]     2      1    0         0
[2,]     0      1    0         1

This allows for capital letters, and should only count whole words (perhaps with an -s plural).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2020-11-20
    • 2011-07-16
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多