【问题标题】:Is there a way to replace a word only if it's paired with another word?只有当它与另一个词配对时,有没有办法替换一个词?
【发布时间】:2021-10-20 16:34:08
【问题描述】:

我有一个正则表达式/字符串替换的困境(对不起,如果这是重复的帖子,我正在寻找解决方案但找不到,但如果我错过了类似的帖子,请告诉我!)。

我们有一个数据集,分为两列:主语和动词。我想删除动词列中的每个模态辅助,但前提是模态与另一个单词。所以我想将字符串“can do”中的“can”替换为“”,但如果“can”单独出现,我不想替换它。我想我可以使用 ifelse 语句,如下面的代码:

all_doubles <- all_doubles %>%
  mutate(modal_removed = ifelse(str_detect(all_doubles$verb_lemma, modal_with_words) == TRUE,
                            str_replace_all("can|could|may|might|shall|should|will|would|need", ""),
                            all_doubles$verb_lemma))

但我无法让正则表达式仅返回带有其他单词的模态辅助词。现在,我正在使用它,但它似乎效果不佳:

modal_with_words <- ".+can|could|may|might|shall|should|will|would|need.+"

任何建议都将不胜感激(我相信有更好的方法来做到这一点)!非常感谢!

【问题讨论】:

  • 你有每个问题的单词列表吗?那么,“do”总是跟在“can”之后吗? (或者,更一般地说,你有一个完整的配对列表吗?)我看到你提到有结构为主语/动词的数据,但不清楚这是我要问的列表还是您尝试操作的数据。
  • 有争议的数据样本可能有助于获得准确的答案

标签: r regex


【解决方案1】:

如果后面有一个空格 + 一个字母,您似乎只想从列表中删除一个模型动词。

在这种情况下,您只需要

rx <- '(?:\\s+|^)(?:can|could|may|might|shall|should|will|would|need)(\\s+[[:alpha:]])'
verb <- c('I can help you.', 'We shall not stop here!')
gsub(rx, '\\1', verb)
# => [1] "I help you."       "We not stop here!"

请参阅R demo(?:\s+|^)(?:can|could|may|might|shall|should|will|would|need)(\s+[[:alpha:]]) 正则表达式匹配

  • (?:\s+|^) - 一个或多个空格或字符串开头
  • (?:can|could|may|might|shall|should|will|would|need) - 单词之一
  • (\s+[[:alpha:]]) - 第 1 组(替换中的\1 指的是这个值):一个或多个空格和一个字母。

【讨论】:

    【解决方案2】:

    如果您的潜在候选者列表相当短且明确,您可以将潜在词连接成正则表达式中的一组查找词。

    #Create what I think the data looks like based on your question
    replacement_targets <- data.frame(subject = c("He", "He", "She", "She", "They", "They", "It", "It"),
     verb = c("can", "can do", "can't help", "can help", "can't do", "can't", "will not help", "will help"))
    
    replacement_targets$string <- paste0(replacement_targets$subject, " ", replacement_targets$verb)
    
    substitution_list <- data.frame(modal_aux = c("can", "can't", "can", "can't", "will", "will not"),
     target = c("do", "do", "help", "help", "help", "help"))
    
    #Constructs a regular expression based on the list of words
    pattern <- paste0("(", paste(unique(substitution_list$modal_aux), collapse = "|"), ").?(", paste(unique(substitution_list$target), collapse="|"), ")")
    
    #Replaces any matches with just the second captured group, where applicable
    gsub(pattern, "\\2", replacement_targets$string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-28
      • 2019-07-08
      • 2011-01-13
      • 2018-06-19
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多