2017-05-07 114 views
0

我試圖替換不包含某些標點的字符串:'/'。替換R中不包含某些標點符號的字符串

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但考慮更多的可能實例,使代碼可以通過他們都會得到。

+0

只是出於好奇,你如何生成POS標籤?我會假設,例如OpenNLP正在標記你的剩菜... –

回答

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" 

這個正則表達式查找的不包含夾在中間的空格或字符串的邊界之間的斜線或空格([^\\/ ]+)字母的字符串。

+0

謝謝!這太棒了! – Rcoding

相關問題