[python] count words in a text

WBOY
Release: 2024-07-21 16:31:42
Original
115 people have browsed it

[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)[" "] #19
Copy after login

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

in other words, it comes with these dunder methods (again, accordingly):

  1. __getitem__(): can access item using dct["key"] notation
  2. __iter__(): return an iterator object to be used in a for loop
  3. __len__(): defines the behavior of len()

The above is the detailed content of [python] count words in a text. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!