【问题标题】:Counting occurence of a word in a text file using R使用R计算文本文件中单词的出现次数
【发布时间】:2016-03-09 09:33:23
【问题描述】:

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

任何想法请帮助我,在此先感谢

【问题讨论】:

  • 使用 R 进行文本挖掘的主题描述得很好,如果你想考虑看看this article,你可以找到进行频率的基本方法对文本文件进行分析。
  • tm 包在这里会有所帮助
  • 您可以索引表,因为级别变成了名称。因此table(mtcars$cyl)['6'] 返回mtcars 中六缸汽车的数量。如果这是你的问题;这有点模棱两可。
  • 好的,谢谢,但我的问题是,如果我想查找“hello”的频率,我该如何在参数中传递“hello”以提取其频率?

标签: r text find-occurrences


【解决方案1】:

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

数据准备

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

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)
}

修改后的(仅全词)

这个函数只匹配full字,下面的解决方案利用this answer

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

【讨论】:

  • 谢谢Konard,你的例子对我帮助很大!!干杯$
  • @Fish 完全没有问题,只是一个旁注,我将data.frame 保留为 occurrence 但如果你想得到你的数字,它将在第二列occurence[,2] 随便哪个更方便。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
相关资源
最近更新 更多