[python] count words in a text

I recently discovered a one-liner to count the words from a text in python:

text = “Tags help people find your post – think of them as the topics or categories that best describe your post.”

from collections import Counter

words = Counter(text)[” …


This content originally appeared on DEV Community and was authored by Adel Bordbari

I recently discovered a one-liner to count the words from a text in python:

text = "Tags help people find your post - think of them as the topics or categories that best describe your post."

from collections import Counter

words = Counter(text)[" "] #19

to put it more accurately, this counts the number of spaces (" ") in a text.

moreover, Counter is a python mapping that creates a dict in which keys are every unique letter from a text, and the corresponding values are the number of occurrences of that letter.

a mapping is an iterable container with a fixed length. this means three things (accordingly):

  1. you can loop through its items
  2. you can check existence of an item using in keyword (e.g., "x" in words)
  3. len(words) returns an integer


This content originally appeared on DEV Community and was authored by Adel Bordbari


Print Share Comment Cite Upload Translate Updates
APA

Adel Bordbari | Sciencx (2024-07-21T06:59:47+00:00) [python] count words in a text. Retrieved from https://www.scien.cx/2024/07/21/python-count-words-in-a-text/

MLA
" » [python] count words in a text." Adel Bordbari | Sciencx - Sunday July 21, 2024, https://www.scien.cx/2024/07/21/python-count-words-in-a-text/
HARVARD
Adel Bordbari | Sciencx Sunday July 21, 2024 » [python] count words in a text., viewed ,<https://www.scien.cx/2024/07/21/python-count-words-in-a-text/>
VANCOUVER
Adel Bordbari | Sciencx - » [python] count words in a text. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/21/python-count-words-in-a-text/
CHICAGO
" » [python] count words in a text." Adel Bordbari | Sciencx - Accessed . https://www.scien.cx/2024/07/21/python-count-words-in-a-text/
IEEE
" » [python] count words in a text." Adel Bordbari | Sciencx [Online]. Available: https://www.scien.cx/2024/07/21/python-count-words-in-a-text/. [Accessed: ]
rf:citation
» [python] count words in a text | Adel Bordbari | Sciencx | https://www.scien.cx/2024/07/21/python-count-words-in-a-text/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.