【问题标题】:Find word match allowing up to n words separation in R在 R 中查找允许最多 n 个单词分离的单词匹配
【发布时间】:2018-03-05 16:52:54
【问题描述】:

希望在 word2 之前匹配 word1,在 word1 和 word2 之间最多允许 5 个单词分隔。例如,如果 word1 是苹果,word2 是芒果,那么模式应该匹配 'apple is a fruit like mango' 但不匹配 'mango is a fruit like apple'(word2 在 word1 之前)或 'apple and orange are fruits, like mango '(超过 5 个字)。 python 中的示例正则表达式是\b(?:word1\W+(?:\w+\W+){0,5}?word2|word2\W+(?:\w+\W+){0,5}?word1)\b。在 R 中识别这种模式的类似模式和函数是什么?

【问题讨论】:

    标签: r regex


    【解决方案1】:
    #DATA
    word1 = "apple"
    word2 = "mango"
    p1 = "apple is a fruit like mango"
    p2 = "apple and orange are fruits, like mango"
    p3 = "mango is a fruit like apple"
    
    #FUNCTION
    foo = function(word1, word2, string){
        ind2 = unlist(gregexpr(word2, string))[1]
        ind1 = unlist(gregexpr(word1, string))[1] 
        nwords = length(unlist(gregexpr(" ", substr(string, ind1, ind2))))
        if(ind2 > ind1 & nwords <= 5){
            substr(string, ind1, ind2 + nchar(word2))
        }else{
            NA
        }
    }
    
    #USAGE
    foo(word1, word2, p1)
    #[1] "apple is a fruit like mango"
    
    foo(word1, word2, p2)
    #[1] NA
    
    foo(word1, word2, p3)
    #[1] NA
    

    【讨论】:

    • 谢谢!这有助于查看底层代码结构。
    【解决方案2】:

    这个有效。将第一个单词计数为 apple,此正则表达式搜索接下来的 4 个,如果在定义的字数限制内找到 mango,则匹配。

    library(stringr)
    > stri <- c('apple is a fruit like mango','apple and orange are fruits, like mango','apple is not a fruit like orange or mango')
    > stri_extract_all(str = stri, regex = 'apple(\\s\\w+){1,4}?.mango')
    
    [[1]]
    [1] "apple is a fruit like mango"
    
    [[2]]
    [1] NA
    
    [[3]]
    [1] NA
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2012-06-29
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多