Use Python built-in functions to quickly count the number of occurrences of a word in text

Source: Internet
Author: User
Tags data structures

Python contains a number of standard programming data structures, such as list (lists), tuple (tuples), dict (dictionaries), and set (), which can be derived from a built-in type for customization if the existing data types do not meet the requirements. Or, use an abstract base class defined in collections as a starting point to build a new container type.

The collections module contains container data types other than the built-in list,dict,tuple. Counter as a container, you can track how many times the same value has been added. This class can be used to implement algorithms for bag and multiset data structures commonly used in other languages.

Initialization
counter supports three forms of initialization, where the counter constructor provides a sequence of elements or a dictionary containing keys and counts, and also uses keyword parameters to map string names to counts.

Simple demo:

#coding =utf-8

Import Collections

str1=[' A ', ' B ', ' C ', ' d ', ' a ', ' a ', ' B ', ' C ']
m=collections. Counter (str1)

print str1 print
m
print m[' a '] #字符a出现的次数
print m[' B '] #字符b出现的次数

Results:

Select an English text below and count the number of occurrences of the word, returning the number of occurrences of a word
What a python line of code can accomplish, don't use two lines

#coding =utf-8

Import Collections
import OS with

open (' Str.txt ') as File1: #打开文本文件
    str1=file1.read (). Split (') #将文章按照空格划分开 

Print original text: \ n%s "% str1
print" \ n the number of occurrences of each word: \ n%s "% collections. Counter (str1)
print collections. Counter (STR1) [' was '] #以字典的形式存储, the key value for each character is the number of times it appears in the text

Results:

Short code, very easy to understand, a look at it.

Related Article

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: info-contact@alibabacloud.com 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.