【问题标题】:Removing dots in acronyms删除首字母缩略词中的点
【发布时间】:2016-04-29 09:17:51
【问题描述】:

我有一个带有“U.S.”等首字母缩略词的向量

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

我可以通过使用 gsub 来做到这一点:

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

但是我如何告诉 R 删除所有可能的首字母缩写词中的所有点(即,也在“U.N.”或“C.I.A.”中)?

【问题讨论】:

标签: r gsub


【解决方案1】:

你可以在这里分词

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

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

【讨论】:

  • 可以对字符串做进一步处理。
  • 我可以用最终的 gsub 表达式删除最后一个点!以便解决方案有效,谢谢!
【解决方案2】:

您的问题似乎与您提供的代码有点不同:您想要替换文本中可能包含不是首字母缩略词/缩写的点的首字母缩略词。

此代码通过搜索重复的大写点组合来提取和识别首字母缩略词(可以在工作流程中手动检查和过滤以确保它没有发现任何奇怪的东西),然后使用来自 @ 的 mgsub 代码替换它们987654321@

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."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多