Python: Count words in a string using Regular Expression
( 48 Articles)

The Python program below counts the number of words in a given string by using a regular expression. Whitespace and any special symbols except the underscore will be ignored.
import re
s = 'Lorem ipsum dolor sit amet, a f @! <> d consectetur adipiscing elit.'
pattern = re.compile(r'\w+')
matches = pattern.findall(s)
print(len(matches))
Output:
11
That’s it. Further reading:
- Python: Calculate Fibonacci number with 4 lines of code
- Tensorflow 2 – Aggregation Operators on Tensors
- Using the isinstance() function in Python 3
- How to run Python 3 with Nodemon on Mac
- Python 3: Convert Datetime to Timestamp and vice versa
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.
Subscribe
0 Comments