【问题标题】:Count word frequency [duplicate]计算词频[重复]
【发布时间】:2016-12-21 10:12:36
【问题描述】:

我正在使用下面的代码来计算给定句子中单词的出现次数

wordCount = function(sentence,word){
splitedVectorString <- c() 
splitedVectorString <- strsplit(sentence," ")
count <- 0

for (j in splitedVectorString) {
  print(length(splitedVectorString))
  print(splitedVectorString)
  print(word)
  if (identical(word,j)) {
    count <- count + 1
    print(count)
  }
}
}

程序运行成功,但计数为 0。我在控制台上将此函数称为

wordCount("This is XYZ and is running late","is")

当我打印分割向量 splitedVectorString 的长度时,它给了我 1。我在分割句子时遇到问题了吗? 确切地说,我不知道出了什么问题。我刚开始学习 R 编程

【问题讨论】:

  • 你可能想读this question,它几乎是一样的(它带有一个向量,但使用strsplit你可以将你的句子转换成一个向量)。
  • 尝试使用 length(grep(word,sentence)) 但仍然得到 1 作为输出。我检查了 splatted 向量的长度,它给了我 1。为什么 splatted 向量“splitedVectorString”给出长度为 1。因此它没有迭代整个向量并且 for 循环只执行一次
  • 使用length(grep("\\&lt;is\\&gt;", strsplit("This is XYZ and is running late", " ")[[1]]))
  • 或者类似sum(sapply(strsplit(sentence," ")[[1]], identical, y = word))(更接近你的功能)

标签: r


【解决方案1】:

你可以做的是:

wordCount = function(sentence,word){

  splitedVectorString <- unlist(strsplit(sentence," "))
  count <- sum(word == splitedVectorString)
  count

  }

你取消列出 strsplit 的结果,这样你就有了一个向量(strsplit 返回一个列表,这就是你得到长度为 1 的原因!)你的句子中的所有单词,然后你对所有等于你的值的值求和词。

表达式word == splitedVectorString 将返回一个与splitedVectorString 长度相同的向量,其中True 和False 取决于向量的特定元素是否与单词相同。

> wordCount("This is XYZ and is running late","is")
[1] 2

【讨论】:

  • 它对我有用。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
相关资源
最近更新 更多