R计数逗号和字符串的数量

scr*_*Owl 8 nlp r

我有一个字符串:

    str1 <- "This is a string, that I've written 
        to ask about a question, or at least tried to."
Run Code Online (Sandbox Code Playgroud)

我怎么会:

1)计算逗号的数量

2)计算'-ion'的出现次数

有什么建议?

Jus*_*tin 21

stringr软件包具有str_count很好地为您完成此功能的功能.

library(stringr)

str_count(str1, ',')
[1] 2
str_count(str1, 'ion')
[1] 1
Run Code Online (Sandbox Code Playgroud)

编辑:

因为我很好奇:

vec <- paste(sample(letters, 1e6, replace=T), collapse=' ')

system.time(str_count(vec, 'a'))
   user  system elapsed 
  0.052   0.000   0.054 

system.time(length(gregexpr('a', vec, fixed=T)[[1]]))
   user  system elapsed 
  2.124   0.016   2.146 

system.time(length(gregexpr('a', vec, fixed=F)[[1]]))
   user  system elapsed 
  0.052   0.000   0.052 
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要注意`gregexpr()`的时间来自**设置`fixed = T`(这里根本不需要).你可能想要为`system.time(length(gregexpr('a',vec)[[1]]))`添加时序,这几乎与`str_count()`的时序相同.这是有道理的,因为`str_count()`本质上是`gregexpr()`的包装器. (2认同)

Ric*_*ton 6

数学文本的一般问题需要正则表达式.在这种情况下,您只想匹配特定字符,但要调用的函数是相同的.你想要的gregexpr.

matched_commas <- gregexpr(",", str1, fixed = TRUE)
n_commas <- length(matched_commas[[1]])

matched_ion <- gregexpr("ion", str1, fixed = TRUE)
n_ion <- length(matched_ion[[1]])
Run Code Online (Sandbox Code Playgroud)

如果你只想在单词的末尾匹配"离子",那么你需要正则表达式.\b代表一个单词边界,你需要逃避反斜杠.

gregexpr(
  "ion\\b", 
  "ionisation should only be matched at the end of the word", 
  perl = TRUE
)
Run Code Online (Sandbox Code Playgroud)