我有一些文本字符串(如下例)。正如你所看到的,每个字符串都被分割成了一个句号或问号。
[1]"I am a Mr."
[2]"asking for help."
[3]"Can you help?"
[4]"Thank you ms."
[5]"or mr."
我想在字符串结尾有缩写的地方进行折叠,比如mr.,mrs.,所以最终的结果将是下面的理想输出。
[1]"I am a Mr. asking for help."
[2]"Can you help?"
[3]"Thank you ms. or mr."
我已经创建了一个向量(称为abbr),其中包含了我所有的缩写,格式如下。
> abbr
[1] "Mr|Mrs|Ms|Dr|Ave|Blvd|Rd|Mt|Capt|Maj"
但我不知道如何在粘贴函数中使用它来折叠。我也试过用gsub(没有用)把缩写后面的句号和空格替换成这样。
lines<-gsub('(?<=abbr\\.\\n)(?=[A-Z])', ' ', lines, perl=FALSE)
我们可以使用 tapply
折叠字符串和 grepl
以创建组来折叠。
x <- c("I am a Mr.", "asking for help.","Can you help?","Thank you ms.", "or Mr.")
#Include all the abbreviations with proper cases
#Note that "." has a special meaning in regex so you need to escape it.
abbr <- 'Mr\\.|Mrs\\.|Ms\\.|Dr\\.|mr\\.|ms\\.'
unname(tapply(x, c(0, head(cumsum(!grepl(abbr, x)), -1)), paste, collapse = " "))
#[1] "I am a Mr. asking for help." "Can you help?" "Thank you ms. or mr."