删除首字母缩略词中的点

时间:2016-04-29 09:17:51

标签: r gsub

我有一个像“美国”这样的首字母缩略词的载体

我想删除字符之间的点,但我不想删除整个文档中的所有点,所以只是缩写词。

我可以使用gsub:

来做到这一点
text <- c("U.S.", "U.N.", "C.I.A")
gsub("U.S.", "US", text)

但是我怎么能告诉R删除所有可能的首字母缩略词中的所有点(即“U.N.”或“C.I.A。”)?

2 个答案:

答案 0 :(得分:1)

你可以在这里进行单词边界

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

或更简单的选项在评论中说明!

答案 1 :(得分: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."
相关问题