我尝试创建一个函数,它返回文本文件中单词出现的次数。 为此,我创建了一个包含文本所有单词的列表。 (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/