2016-04-29 90 views
-2

我有一個帶有「U.S.」在首字母縮寫詞中刪除點

我想刪除字符之間的點,但我不想刪除整個文檔中的所有點,所以只是在縮略詞中。

我可以通過使用GSUB做到這一點:

text <- c("U.S.", "U.N.", "C.I.A") 
gsub("U.S.", "US", text) 

但我怎麼可以讓R能夠消除所有可能的首字母縮寫詞的所有點(即,也是在「聯合國」或「C.I.A.」)?

+2

'gsub(「\\。」,「」,text)'? – mtoto

+1

https://regex101.com/r/nQ3jI8/1? –

回答

1

,您可以在這裏單詞邊界

gsub('\\b\\.','',vec) 

或簡單的選擇在評論中陳述!

+2

但是這不會刪除最後一個點.. –

+0

您可以對字符串進行進一步處理。 –

+0

我可以用最終的gsub表達式刪除最後一個點!所以解決方案的作品,謝謝! – feder80

1

您的問題似乎與您提供的代碼有點不同:您想要替換文本中可能包含點的首字母縮寫詞,其中不是首字母縮寫詞/縮寫詞。

此代碼提取物和通過搜索反覆資本墨滴組合(可以手動檢查和過濾中旬的工作流程,以確保它不會拿起什麼奇怪)標識的縮寫,然後使用mgsub代碼Replace multiple arguments with gsub

替換它們
text1 <- c("The U.S. and the C.I.A. are acronyms. They should be matched.") 
m <- gregexpr("([A-Z]\\.)+", text1) 
matches <- regmatches(text1, m)[[1]] 
matches_nodot <- sapply(matches, gsub, pattern = "\\.", replacement = "") 

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 
} 


text2 <- mgsub(matches, matches_nodot, text1) 
text2 
# [1] "The US and the CIA are acronyms. They should be matched." 
相關問題