s <- "height(female), weight, BMI, and BMI."
在上面的字符串中,“BMI”这个单词被重复了两次。我想把这个字符串变成:
"height (female), weight, and BMI."
我已经尝试以下方法将字符串拆分为唯一部分:
> unique(strsplit(s, " ")[[1]])
[1] "height" "(female)," "weight," "BMI," "and" "BMI."
但是由于"BMI"和"BMI."不是相同的字符串,使用unique
并不能消除其中一个。
编辑:我该如何处理重复短语?(例如使用“身体质量指数”代替BMI)
s <- "height (female), weight, weight, body mass index, body mass index."
s <- stringr::str_replace(s, "(?<=, |^)\\b([()\\w\\s]+),\\s(.*?)((?: and)?(?=\\1))", "\\2")
> stringr::str_replace(s, "(\\w+)(\\(.*?\\))", "\\1 \\2")
[1] "height (female), weight, body mass index, body mass index."
s
的结构是否总是"<keyword>,<keyword>,...,and <keyword>"
?一个关键字可以包含逗号、空格、单词“and”等吗? - Maurits Everss
的结构始终为“<关键词>,<关键词>,...,和<关键词>。” 一些“<关键词>”可能包含“(男)”或“(女)”。 每个“<关键词>”后面都跟着“,”,而最后一个<关键词>前面则是“和”。 - Adrianheight(female)
会发生什么?或者这种情况不会发生吗? - andrew_reecestringr::str_replace(s, " BMI,", "")
这样的操作? - andrew_reece