我需要以编程方式在两行中拆分/包装一些多字句,说“这是一个多字句的例子”。如何用"\n"
替换最接近句子中间的白色空间?
你可以使用strwrap
玩一些东西。
这是一个非常基本的实现:
sentSplit <- function(string, tolerance = 1.05, collapse = "\n") {
paste(strwrap(string, width = nchar(string)/2 * tolerance), collapse = collapse)
}
sent <- "This is an example of a multi-word sentence"
sentSplit(sent)
# [1] "This is an example of\na multi-word sentence"
cat(sentSplit(sent))
# This is an example of
# a multi-word sentence
“容差”参数基本上是因为在某些情况下,它可能会将字符串拆分为3个部分,此时,您可以增加容差以最多包含两个拆分。
使用strwrap()
的简单解决方案:
x <- "This is an example of a multi-word sentence"
wrapInTwo <- function(x, fraction = 0.6) strwrap(x, width = fraction * nchar(x))
wrapInTwo(x)
[1] "This is an example of a" "multi-word sentence"