【问题标题】:Use grepl to search either of multiple substrings in a text [duplicate]使用 grepl 在文本中搜索多个子字符串中的一个 [重复]
【发布时间】:2014-10-11 21:44:42
【问题描述】:

我在 R 中使用 grepl() 来搜索我的文本中是否存在以下任一 genres。我现在正在这样做:

grepl("Action", my_text) |
grepl("Adventure", my_text) |
grepl("Animation", my_text) |
grepl("Biography", my_text) |
grepl("Comedy", my_text) |
grepl("Crime", my_text) |
grepl("Documentary", my_text) |
grepl("Drama", my_text) |
grepl("Family", my_text) |
grepl("Fantasy", my_text) |
grepl("Film-Noir", my_text) |
grepl("History", my_text) |
grepl("Horror", my_text) |
grepl("Music", my_text) |
grepl("Musical", my_text) |
grepl("Mystery", my_text) |
grepl("Romance", my_text) |
grepl("Sci-Fi", my_text) |
grepl("Sport", my_text) |
grepl("Thriller", my_text) |
grepl("War", my_text) |
grepl("Western", my_text)

有没有更好的方法来编写这段代码?我可以将所有类型放在一个数组中,然后以某种方式使用grepl() 吗?

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    您可以将流派与“或”| 分隔符粘贴在一起,然后将其作为单个正则表达式通过 grepl 运行。

    x <- c("Action", "Adventure", "Animation", ...)
    grepl(paste(x, collapse = "|"), my_text)
    

    这是一个例子。

    x <- c("Action", "Adventure", "Animation")
    my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.")
    grepl(paste(x, collapse = "|"), my_text)
    # [1]  TRUE FALSE  TRUE
    

    【讨论】:

      【解决方案2】:

      您可以循环浏览流派列表或向量,如下所示:

      genres <- c("Action",...,"Western")
      sapply(genres, function(x) grepl(x, my_text))
      

      要回答您的问题,如果您只想知道结果的any 元素是否为TRUE,您可以使用any() 函数。

      any(sapply(genres, function(x) grepl(x, my_text)))
      

      很简单,如果 的任何元素为 TRUE,any 将返回 TRUE。

      【讨论】:

      • 这让我接近我正在寻找的东西。但我在这里得到的是每种类型的 TRUE/FALSE 值。如果我有 20 种类型的数组,如果 my_text 中包含其中一种类型,我会得到 19 个 FALSE 值和 1 个 TRUE 值。我想从这句话中得到最终结果 19 FALSE 和 1 TRUE 最终等于 TRUE。你明白我在说什么吗?我该怎么做?
      • 我在此之上做了一个 if 语句来查看条件是否返回 true。
      猜你喜欢
      • 2015-05-05
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      相关资源
      最近更新 更多