Yun
Yun

Reputation: 89

How to connect sentences with invalid line breaks

I have a long character with several sentences in a row.

ex :

"I have a
apple.
but I like banana."

It's irregularly lined up like this. Is there any way to automatically concatenate this?

result :

"I have a apple.
but I like banana."

Upvotes: 0

Views: 39

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389055

I added few more lines to the input for testing purpose.

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.

Upvotes: 2

Related Questions