如何连接带有无效换行符的句子
How to connect sentences with invalid line breaks
我有一个长字连着好几句
例如:
"I have a
apple.
but I like banana."
不规则的排列成这样。有什么方法可以自动连接这个吗?
结果:
"I have a apple.
but I like banana."
出于测试目的,我在输入中添加了更多行。
x <- "I have a
apple.
but I like banana.
This is new text.
and another one
to complete it."
#split the string on newline
tmp <- trimws(strsplit(x, '\n')[[1]])
#Create a grouping variable which increments every time the statement
#ends on ".", paste each group together.
tapply(tmp, c(0, head(cumsum(grepl('\.$', tmp)), -1)), function(x) paste0(x, collapse = ' ')) |>
#Collapse data in one string
paste0(collapse = '\n') |>
#For printing purpose.
cat()
#I have a apple.
#but I like banana.
#This is new text.
#and another one to complete it.
我有一个长字连着好几句
例如:
"I have a
apple.
but I like banana."
不规则的排列成这样。有什么方法可以自动连接这个吗?
结果:
"I have a apple.
but I like banana."
出于测试目的,我在输入中添加了更多行。
x <- "I have a
apple.
but I like banana.
This is new text.
and another one
to complete it."
#split the string on newline
tmp <- trimws(strsplit(x, '\n')[[1]])
#Create a grouping variable which increments every time the statement
#ends on ".", paste each group together.
tapply(tmp, c(0, head(cumsum(grepl('\.$', tmp)), -1)), function(x) paste0(x, collapse = ' ')) |>
#Collapse data in one string
paste0(collapse = '\n') |>
#For printing purpose.
cat()
#I have a apple.
#but I like banana.
#This is new text.
#and another one to complete it.