Using R code, read in a text file and
output a numbered list of the 5 longest sentences from the longest to shortest sentence.
# Load necessary library
library(stringr)
# Read the text file
text <- "The Justice League is comprised of many superheroes. Some heroes are from earth others are from other distant planets. Some of which are listed below. Batman is from Gotham City, and is a master of martial-arts, chemistry, and criminal forensics. Batman also trains his sidekicks to fight crime like Robin, Bat Girl, and Night Wing . Superman is from from the planet Krypton and has laser eyes, super-strength, and flight. Martian Manhunter is from Mars and can shape shift. Green Lantern is a member of the Green lantern Corp and has the power to create, destroy or move objects with his ring. Wonder-woman is from the island of Themescara and has the power of flight, super-strength, and her lasso of truth. The Hero Flash has the power of the speed force, allowing him to move faster than the speed of light."
# Split the text into sentences
sentences <- unlist(str_split(text, "(?<=[.!?])\s+"))
# Calculate the length of each sentence
sentence_lengths <- nchar(sentences)
# Get the indices of the longest 5 sentences
longest_indices <- order(sentence_lengths, decreasing = TRUE)[1:5]
# Output the longest 5 sentences
longest_sentences <- sentences[longest_indices]
print(longest_sentences, length(longest_sentences) )
# Print the longest 5 sentences
cat(paste(longest_sentences, collapse = "n"))
New contributor
mohamed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2