Code for Counting Sentences in Text using stringr Package
R
text <- "This is R program for counting number of sentences in text. This program is for GFG article . And it is using stringr package for counting." sentences <- unlist ( strsplit (text, "[.!?]" )) num_sentences <- length (sentences) cat ( "Number of sentences using unlist and strsplit :" , num_sentences) |
Output:
Number of sentences using unlist and strsplit : 3
- First we store text in text variable .
- Then we use strsplit to split text using regular expression .
- unlist() – on above split output to convert it to list and store it in sentences variable.
- length() is used to find number of sentences in sentences variable.
Finally we use cat to display the sentence count as below. As there are 3 sentences in the text ending with full stop(.) the output will be 3 .
How to count the number of sentences in a text in R
A fundamental task in R that is frequently used in text analysis and natural language processing is counting the number of sentences in a text. Sentence counting is necessary for many applications, including language modelling, sentiment analysis, and text summarization. In this article, we’ll look at various techniques and R packages for quickly and correctly counting the amount of phrases in a given text using R.