Use Python's counter built-in function to count the number of words in a text

Source: Internet
Author: User
Tags iterable shallow copy

Counter is a class within the Colletions

Can be understood as a simple counter, you can count the number of characters appearing, examples are as follows

ImportCOLLECTIONSSTR1=['a','a','b','D']m=collections. Counter (STR1)Print(m) str2=['You're','Good','You're','You're']m1=collections. Counter (STR2)Print(M1)


Counter ({' A ': 2, ' B ': 1, ' d ': 1})
Counter ({' You ': 3, ' Good ': 1})

This makes it easy to count the number of characters in the text by combining text readings.

Here's a detailed introduction

by Learning Blog: Pythoner Address: Module

This module contains some special containers in python other than dict,set,list,tuple

    • Ordereddict class: A sort dictionary, which is a subclass of a dictionary. Introduced since 2.7.
    • Namedtuple () function: A named tuple, is a factory function. Introduced since 2.6.
    • Counter class: The Hashable object count, which is a subclass of the dictionary. Introduced since 2.7.
    • Deque: Bidirectional queue. Introduced since 2.4.
    • Defaultdict: Use the factory function to create a dictionary so that the missing dictionary key is not considered. Introduced since 2.5.

Counter class

The purpose of the counter class is to track the number of occurrences of a value.

It is an unordered container type, stored in the form of a dictionary key-value pair, where the element is counted as the key and its count as value. The count value can be any Interger (including 0 and negative numbers).

First, there are four methods of creation

>>> C = Counter ()  #  Create an empty Counter class >>> c = Counter ('adasdasd ')  # create from a Iterable object (list, tuple, dict, string, etc.) >>> C = Counter ({'a')  b': 2})  #  created from a Dictionary object >>> c = Counter (a=4, b=2)  # create from a set of key-value pairs

Returns 0 instead of Keyerror when the key being accessed does not exist, otherwise returns its count.

>>> C = Counter ("abcdefgab")>>> c["a"  ]2>>> c["C"]1>>> c["H  "]0
2.3 Update for counters (update and subtract)

You can use one Iterable object or another counter object to update the key value.

The update of the counter includes two additions and decreases. Where, increase the use of the update () method:

>>> C = Counter ('which')>>> C.update ('Witch')#update with another Iterable object>>> c['h']3>>> d = Counter ('Watch')>>> C.update (d)#update with another counter object>>> c['h']4

Reduce the use of the Subtract () method:

>>> C = Counter ('which')>>> C.subtract ('Witch')#update with another Iterable object>>> c['h']1>>> d = Counter ('Watch')>>> C.subtract (d)#update with another counter object>>> c['a']-1
2.4-Key deletion

When the count value is 0 o'clock, it does not mean that the element is deleted, and the deleted element should be used del .

>>> C = Counter ("ABCDCBA")>>>Ccounter ({'a': 2,'C': 2,'b': 2,'D': 1})>>> c["b"] =0>>>Ccounter ({'a': 2,'C': 2,'D': 1,'b': 0})>>>delc["a"]>>>Ccounter ({'C': 2,'b': 2,'D': 1})
2.5 elements ()

Returns an iterator. How many times the element is repeated, and how many of that element are included in the iterator. Element permutations are not in a deterministic order, and elements less than 1 are not included.

>>> C = Counter (a=4, b=2, c=0, d=-2)>>> list (c.elements ()) ['a ' ' a ' ' a ' ' a ' ' b ' ' b ']
2.6 Most_common ([n])

Returns a list of TOPN. If n is not specified, all elements are returned. When multiple element count values are the same, the permutations are in an indeterminate order.

>>> C = Counter ('Abracadabra')>>>C.most_common () [('a', 5), ('R', 2), ('b', 2), ('C', 1), ('D', 1)]>>> C.most_common (3)[('a', 5), ('R', 2), ('b', 2)]
2.8 Shallow Copy copy

>>> C = Counter ("ABCDCBA")>>>Ccounter ({'a': 2,'C': 2,'b': 2,'D': 1})>>> d =c.copy ()>>>Dcounter ({'a': 2,'C': 2,'b': 2,'D': 1})
2.9 Arithmetic and set operations
>>> C = Counter (A=3, b=1)>>> d = Counter (A=1, b=2)>>> C + D#C[x] + d[x]Counter ({'a': 4,'b': 3})>>> c-d#subtract (only elements with positive count are preserved)Counter ({'a': 2})>>> C & D#intersection: Min (c[x], d[x])Counter ({'a': 1,'b': 1})>>> C | D#set: Max (C[x], d[x])Counter ({'a': 3,'b': 2})

Use Python's counter built-in function to count the number of words in a text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.