r - 使用 R 计算文本文件中单词的出现次数

标签 r text find-occurrences

我尝试创建一个函数,它返回文本文件中单词出现的次数。 为此,我创建了一个包含文本所有单词的列表。 (a、c、、c、d、e、f 位于示例单词中)

[[1]]

 [1] a  

 [2] f 

 [3] e       

 [4] a 

[[2]] 

 [1] f 

 [2] f

 [3] e

我创建一个表来存储每个单词的出现次数值

table(unlist(list))

  a b c d e

  3 3 2 1 1

我现在的问题是如何提取参数中单词出现的值。 该函数将具有以下结构

GetOccurence <- function(word, table)
{
   return(occurence)
} 

任何想法请帮助我,提前致谢

最佳答案

要回答有关您的职能的问题,您可以采用以下方法。

数据准备

为了重现性,我使用了公开可用的数据并对其进行了一些清理。

library(tm)
data(acq)

# Basic cleaning
acq <- tm_map(acq, removePunctuation)  
acq <- tm_map(acq, removeNumbers)     
acq <- tm_map(acq, tolower)     
acq <- tm_map(acq, removeWords, stopwords("english"))  
acq <- tm_map(acq, stripWhitespace)   
acq <- tm_map(acq, PlainTextDocument) 

# Split list into words
wrds <- strsplit(paste(unlist(acq), collapse = " "), ' ')[[1]]
# Table
tblWrds <- table(wrds)

函数

GetOccurence <- function(word, table) {
    occurence <- as.data.frame(table)
    occurence <- occurence[grep(word, occurence[,1]), ]
    return(occurence)
}

已修改(仅限完整单词)

此函数将仅匹配完整单词,下面的解决方案利用 this answer .

GetOccurence <- function(word, table) {
    occurence <- as.data.frame(table)
    word <- paste0("\\b", word, "\\b")
    occurence <- occurence[grep(word, occurence[,1]), ]
    return(occurence)
}

关于r - 使用 R 计算文本文件中单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887730/

相关文章:

r - 在 R 中的同一个表中获取列数和比例

swift - 强制 UIButton 只有一个标题行

Rails 应用程序 user_mailer 中的 HTML 与文本

r - 如何计算R中的条件发生次数?

R 在绘图上翻转 XY 轴

c++ - g++ ld 找不到 x86_64 架构的 RInside 符号

r - 如何在R中的for循环中逐项应用功能

c++ - 使用 FreeType/GLFW 根本不呈现文本

string - 使用scala查找给定字符串是另一个字符串的子字符串的次数

python - 使用函数将每个第二个单词替换为单词 'hello'