3
Row<-c(1,2,3,4,5)
Content<-c("I love cheese", "whre is the fish", "Final Countdow", "show me your s", "where is what")
Data<-cbind(Row, Content)
View(Data)

我想创建一个函数来告诉我每行有多少单词是错误的。

一个中间步骤是让它看起来像这样:

Row<-c(1,2,3,4,5)
Content<-c("I love cheese", "whre is the fs", "Final Countdow", "show me your s", "where is     what")
MisspelledWords<-c(NA, "whre, fs", "Countdow","s",NA)
Data<-cbind(Row, Content,MisspelledWords)

我知道我必须使用 aspell,但是我在仅对行执行 aspell 而不总是直接在整个文件上执行 aspell 时遇到问题,最后我想计算每行有多少单词是错误的为此我将采用以下代码:计算R中字符串中的单词数?

4

2 回答 2

6

要使用aspell,您必须使用文件。使用函数将列转储到文件、运行aspell并获取计数非常简单(但如果您有一个大矩阵/数据框,它的效率就不会那么高)。

countMispelled <- function(words) {  

  # do a bit of cleanup (if necessary)
  words <- gsub("  *", " ", gsub("[[:punct:]]", "", words))

  temp_file <- tempfile()
  writeLines(words, temp_file);
  res <- aspell(temp_file)
  unlink(temp_file)  

  # return # of mispelled words
  length(res$Original)

}

Data <- cbind(Data, Errors=unlist(lapply(Data[,2], countMispelled)))

Data

##      Row Content             Errors
## [1,] "1" "I love cheese"     "0"   
## [2,] "2" "whre is thed fish" "2"   
## [3,] "3" "Final Countdow"    "1"   
## [4,] "4" "show me your s"    "0"   
## [5,] "5" "where is what"     "0"  

使用数据框与矩阵(我刚刚使用您提供的内容)可能会更好,因为您可以以这种方式保持Row数字Errors

于 2014-09-16T16:43:44.463 回答
6

这篇文章的启发,这里尝试使用which_misspelledcheck_spellingin library(qdap)

library(qdap)

# which_misspelled
n_misspelled <- sapply(Content, function(x){
  length(which_misspelled(x, suggest = FALSE))
})

data.frame(Content, n_misspelled, row.names = NULL)
#             Content n_misspelled
# 1     I love cheese            0
# 2    whre is the fs            2
# 3    Final Countdow            1
# 4    show me your s            0
# 5 where is     what            0


# check_spelling
df <- check_spelling(Content, n.suggest = 0)                        

n_misspelled <- as.vector(table(factor(df$row, levels = Row)))

data.frame(Content, n_misspelled)
#             Content n_misspelled
# 1     I love cheese            0
# 2    whre is the fs            2
# 3    Final Countdow            1
# 4    show me your s            0
# 5 where is     what            0
于 2014-09-16T17:28:41.253 回答