Counting Sentences in Text using R and strcount()
R
if (! require (stringr)) { install.packages ( "stringr" ) library (stringr) } 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. And is it working ?" sentence_pattern <- "[.!?]" num_sentences <- str_count (text, sentence_pattern) cat ( "Number of sentences using stringr :" , num_sentences, "\n" ) |
Output:
Number of sentences using stringr : 4
- First we install the stringr package if it is not installed and store text similarly as above in text variable.
- Then we store our regular expression in sentence_pattern variable .
- str_count() to count sentences by matching text on regular expression .
Finally we will display the sentence count using cat. Here in text there are four sentences in total 3 ending with full stop(.) and one ending with question mark(?) .Hence the output is 4
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.