【问题标题】:How to find string in a character in R如何在R中的字符中查找字符串
【发布时间】:2014-09-16 18:35:34
【问题描述】:

我知道这是一个非常幼稚的问题,但我尝试了很多但没有找到一种方法来计算 R 中字符串中指定子字符串的出现次数。

例如:

str <- "Hello this is devavrata! here, say again hello"

现在我想查找hello 的出现次数,忽略大小写。在这个例子中,答案应该是 2。
编辑:我想知道当我找到 ello th 然后 str_count 会出现 1 但我想要由空格包围的确切单词意味着在这种情况下它应该给出zero
例如,如果我想在特定的字符串中找到very good,例如:-

It is very good to speak like thevery good

并且出现应该是1,而不是2。希望你能理解。

【问题讨论】:

  • 您能否在string 中显示它以及您的预期结果。
  • 我做了一些更新,看看是否有帮助。

标签: r string


【解决方案1】:

你也可以试试:

 library(stringi)
  stri_count(str, regex="(?i)hello")
  #[1] 2


  str1 <- "It is very good to speak like thevery good"
  stri_count(str1, regex="\\b(?i)very good\\b")
 #[1] 1

【讨论】:

  • 我想知道当我找到ello th 然后str_count 会出现1 但我想要由空格包围的确切单词出现意味着在这种情况下它应该给出zero .
  • 谢谢它很好用!!做stringi 包需要加载lattice
  • @Devavrata 我不知道它是否需要 lattice 作为依赖,但有一点是这些操作非常快。
【解决方案2】:

我迟到了,但我认为 qdap 包中的 termco 函数完全符合您的要求。您可以使用前导和/或尾随空格来控制单词边界,如下例所示:

x <- c("Hello this is devavrata! here, say again hello",
    "It is very good to speak like thevery good")

library(qdap)
(out <- termco(x, id(x), list("hello", "very good", " very good ")))

##   x word.count     hello very good very good
## 1 1          8 2(25.00%)         0         0
## 2 2          9         0 2(22.22%) 1(11.11%)

## To get a data frame of pure counts:
out %>% counts()

##   x word.count hello very good very good
## 1 1          8     2         0         0
## 2 2          9     0         2         1

【讨论】:

    【解决方案3】:

    也许最简单和最直接的方法是使用str_count from stringr

    str <- "Hello this is devavrata! here, say again hello"
    library(stringr)
    str_count(str, ignore.case("hello"))
    # [1] 2
    

    两个基本 R 方法是

    length(grep("hello", strsplit(str, " ")[[1]], ignore.case = TRUE))
    # [1] 2
    

    sum(gregexpr("hello", str, ignore.case = TRUE)[[1]] > 0)
    # [1] 2
    

    【讨论】:

    • 谢谢...我已经尝试了 grep,但是当我必须找到像 "very good" 这样的字符串时它会出错,这是我面临的主要问题
    • @Devavrata - 字符串匹配非常具体,因此需要针对不同的匹配条件进行调整。
    • 没错,但在我的方案中这是主要问题,但这已由str_count解决。我不想将我的字符串分成向量。
    猜你喜欢
    • 2014-11-29
    • 2011-01-11
    • 2022-12-10
    • 2021-01-18
    • 2020-05-12
    • 2018-11-24
    • 2017-03-22
    • 2019-10-01
    相关资源
    最近更新 更多