替换R中不包含特定标点符号的字符串

时间:2017-05-07 17:38:44

标签: r regex

我的目标是替换不包含特定标点符号的字符串:'/'。

sentence = 'I/NP to/INF this/NP like/CON that/NP Peter wow er ! is'

[彼得,哇,!,呃,是]这些元素没有被'/'标记,所以有必要用'/ UN'标记它们。

这是我为此尝试过的

    seg = unlist(strsplit(sentence, '[[:space:]]+'))
    segment = seg[!grepl('\\/',seg)]
    replace = gsub('(\\S+)','\\1/UN',segment)

    library(stringr)
    mgsub <- function(pattern, replacement, x, ...) {
      if (length(pattern)!=length(replacement)) {
        stop("pattern and replacement do not have the same length.")
      }
      result <- x
      for (i in 1:length(pattern)) {
        result <- gsub(pattern[i], replacement[i], result, ...)
      }
      result
    }

    mgsub(segment, replace, sentence)

然而,遗憾的是,我得到的是以下结果。

[1] "I/NP to/INF this/UN/NP like/CON that/NP Peter/UN/UN wow/UN er/UN !/UN is/UN"

这是我的目标:

[1] "I/NP to/INF this/NP like/CON that/NP Peter/UN wow/UN er/UN !/UN is/UN"

请不要犹豫不决 - sentence但请考虑更多可能的示例,以便代码可以通过所有示例。

1 个答案:

答案 0 :(得分:3)

如果您要将/UN添加到不包含/的所有字词,您可以使用gsub。例如

gsub("(?<=^| )([^\\/ ]+)(?= |$)","\\1\\2/UN\\3", sentence, perl=T)
# [1] "I/NP to/INF this/NP like/CON that/NP Peter/UN wow/UN er/UN !/UN is/UN"

此正则表达式查找一个字母字符串,这些字母不包含斜杠或空格([^\\/ ]+)夹在空格或字符串边界之间。