Count word in list python

Im trying to find the number of whole words in a list of strings, heres the list

mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point  blanchardstown"] 

expected outcome:

4
1
2
3

There are 4 words in mylist[0], 1 in mylist[1] and so on

for x, word in enumerate(mylist):
    for i, subwords in enumerate(word):
        print i

Totally doesnt work….

What do you guys think?

asked Sep 16, 2013 at 11:45

Boosted_d16's user avatar

Boosted_d16Boosted_d16

13k34 gold badges95 silver badges156 bronze badges

1

Use str.split:

>>> mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point  blanchardstown"] 
>>> for item in mylist:
...     print len(item.split())
...     
4
1
2
3

answered Sep 16, 2013 at 11:50

Ashwini Chaudhary's user avatar

Ashwini ChaudharyAshwini Chaudhary

242k58 gold badges456 silver badges502 bronze badges

The simplest way should be

num_words = [len(sentence.split()) for sentence in mylist]

answered Sep 16, 2013 at 11:50

Hari Menon's user avatar

Hari MenonHari Menon

33.1k14 gold badges82 silver badges108 bronze badges

You can use NLTK:

import nltk
mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point  blanchardstown"]
print(map(len, map(nltk.word_tokenize, mylist)))

Output:

[4, 1, 2, 3]

answered Aug 11, 2015 at 23:58

Franck Dernoncourt's user avatar

for x,word in enumerate(mylist):
    print len(word.split())

answered Sep 16, 2013 at 12:12

Srinivasreddy Jakkireddy's user avatar

a="hello world aa aa aa abcd  hello double int float float hello"
words=a.split(" ")
words
dic={}
for word in words:
    if dic.has_key(word):
        dic[word]=dic[word]+1
    else:
        dic[word]=1
dic

iScrE4m's user avatar

iScrE4m

8821 gold badge11 silver badges29 bronze badges

answered Sep 13, 2016 at 10:30

Usama Chitapure's user avatar

2

We can count the number of a word’s ocurrence in a list using the Counter function.

from collection import Counter

string = ["mahesh","hello","nepal","nikesh","mahesh","nikesh"]

count_each_word = Counter(string)
print(count_each_word)

Output:

Counter({mahesh:2},{hello:1},{nepal:1},{nikesh:2})

Hoppeduppeanut's user avatar

answered May 16, 2019 at 1:31

Mahesh Acharya's user avatar

1

This is another solution:

You can clean your data first and then count the result, something like that:

mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point  blanchardstown"] 
for item in mylist:
    for char in "-.,":
        item = item.replace(char, '')
        item_word_list = item.split()
    print(len(item_word_list))

The result:

4
1
2
3

answered Aug 26, 2019 at 16:38

neosergio's user avatar

neosergioneosergio

4325 silver badges14 bronze badges

mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
flage = True
for string1 in mylist:
    n = 0
    for s in range(len(string1)):
        if string1[s] == ' ' and flage == False:
            n+=1
        if string1[s] == ' ':
            flage = True
        else:
            flage = False
    print(n+1)

answered Mar 11, 2020 at 19:55

sshivanshu992's user avatar

lista="Write a Python function to count the number of occurrences of a given characte Write a  of occurrences of a given characte"

dic=lista.split(" ")
wcount={} 
for i in dic:
  if i  in wcount:
    wcount[i]+=1
  else:
    wcount[i]=1 
print(wcount)

picture with solution

Michał Zaborowski's user avatar

answered Mar 30 at 10:45

Debashish Das's user avatar

Introduction

Counting the word frequency in a list element in Python is a relatively common task — especially when creating distribution data for histograms.

Say we have a list ['b', 'b', 'a'] — we have two occurrences of «b» and one of «a». This guide will show you three different ways to count the number of word occurrences in a Python list:

  • Using Pandas and NumPy
  • Using the count() Function
  • Using the Collection Module’s Counter
  • Using a Loop and a Counter Variable

In practice, you’ll use Pandas/Numpy, the count() function or a Counter as they’re pretty convenient to use.

Using Pandas and NumPy

The shortest and easiest way to get value counts in an easily-manipulable format (DataFrame) is via NumPy and Pandas. We can wrap the list into a NumPy array, and then call the value_counts() method of the pd instance (which is also available for all DataFrame instances):

import numpy as np
import pandas as pd

words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']

pd.value_counts(np.array(words))

This results in a DataFrame that contains:

hello      3
goodbye    1
bye        1
howdy      1
hi         1
dtype: int64

You can access its values field to get the counts themselves, or index to get the words themselves:

df = pd.value_counts(np.array(words))

print('Index:', df.index)
print('Values:', df.values)

This results in:

Index: Index(['hello', 'goodbye', 'bye', 'howdy', 'hi'], dtype='object')

Values: [3 1 1 1 1]

Using the count() Function

The «standard» way (no external libraries) to get the count of word occurrences in a list is by using the list object’s count() function.

The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

The complexity of the count() function is O(n), where n is the number of factors present in the list.

The code below uses count() to get the number of occurrences for a word in a list:

words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']

print(f'"hello" appears {words.count("hello")} time(s)')
print(f'"howdy" appears {words.count("howdy")} time(s)')

This should give us the same output as before using loops:

"hello" appears 3 time(s)
"howdy" appears 1 time(s)

The count() method offers us an easy way to get the number of word occurrences in a list for each individual word.

Using the Collection Module’s Counter

The Counter class instance can be used to, well, count instances of other objects. By passing a list into its constructor, we instantiate a Counter which returns a dictionary of all the elements and their occurrences in a list.

From there, to get a single word’s occurrence you can just use the word as a key for the dictionary:

from collections import Counter

words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']

word_counts = Counter(words)

print(f'"hello" appears {word_counts["hello"]} time(s)')
print(f'"howdy" appears {word_counts["howdy"]} time(s)')

This results in:

"hello" appears 3 time(s)
"howdy" appears 1 time(s)

Using a Loop and a Counter Variable

Ultimately, a brute force approach that loops through every word in the list, incrementing a counter by one when the word is found, and returning the total word count will work!

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Of course, this method gets more inefficient as the list size grows, it’s just conceptually easy to understand and implement.

The code below uses this approach in the count_occurrence() method:

def count_occurrence(words, word_to_count):
    count = 0
    for word in words:
        if word == word_to_count:
          # update counter variable
            count = count + 1
    return count


words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
print(f'"hello" appears {count_occurrence(words, "hello")} time(s)')
print(f'"howdy" appears {count_occurrence(words, "howdy")} time(s)')

If you run this code you should see this output:

"hello" appears 3 time(s)
"howdy" appears 1 time(s)

Nice and easy!

Most Efficient Solution?

Naturally — you’ll be searching for the most efficient solution if you’re dealing with a large corpora of words. Let’s benchmark all of these to see how they perform.

The task can be broken down into finding occurrences for all words or a single word, and we’ll be doing benchmarks for both, starting with all words:

import numpy as np
import pandas as pd
import collections

def pdNumpy(words):
    def _pdNumpy():
        return pd.value_counts(np.array(words))
    return _pdNumpy

def countFunction(words):
    def _countFunction():
        counts = []
        for word in words:
            counts.append(words.count(word))
        return counts
    return _countFunction

def counterObject(words):
    def _counterObject():
        return collections.Counter(words)
    return _counterObject
    
import timeit

words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']

print("Time to execute:n")
print("Pandas/Numpy: %ss" % timeit.Timer(pdNumpy(words)).timeit(1000))
print("count(): %ss" % timeit.Timer(countFunction(words)).timeit(1000))
print("Counter: %ss" % timeit.Timer(counterObject(words)).timeit(1000))

Which results in:

Time to execute:

Pandas/Numpy: 0.33886080000047514s
count(): 0.0009540999999444466s
Counter: 0.0019409999995332328s

The count() method is extremely fast compared to the other variants, however, it doesn’t give us the labels associated with the counts like the other two do.

If you need the labels — the Counter outperforms the inefficient process of wrapping the list in a NumPy array and then counting.

On the other hand, you can make use of DataFrame’s methods for sorting or other manipulation that you can’t do otherwise. Counter has some unique methods as well.

Ultimately, you can use the Counter to create a dictionary and turn the dictionary into a DataFrame as as well, to leverage the speed of Counter and the versatility of DataFrames:

df = pd.DataFrame.from_dict([Counter(words)]).T

If you don’t need the labels — count() is the way to go.

Alternatively, if you’re looking for a single word:

import numpy as np
import pandas as pd
import collections

def countFunction(words, word_to_search):
    def _countFunction():
        return words.count(word_to_search)
    return _countFunction

def counterObject(words, word_to_search):
    def _counterObject():
        return collections.Counter(words)[word_to_search]
    return _counterObject

def bruteForce(words, word_to_search):
    def _bruteForce():
        counts = []
        count = 0
        for word in words:
            if word == word_to_search:
              # update counter variable
                count = count + 1
            counts.append(count)
        return counts
    return _bruteForce
    
import timeit

words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']

print("Time to execute:n")
print("count(): %ss" % timeit.Timer(countFunction(words, 'hello')).timeit(1000))
print("Counter: %ss" % timeit.Timer(counterObject(words, 'hello')).timeit(1000))
print("Brute Force: %ss" % timeit.Timer(bruteForce(words, 'hello')).timeit(1000))

Which results in:

Time to execute:

count(): 0.0001573999998072395s
Counter: 0.0019498999999996158s
Brute Force: 0.0005682000000888365s

The brute force search and count() methods outperform the Counter, mainly because the Counter inherently counts all words instead of one.

Conclusion

In this guide, we explored finding the occurrence of the word in a Python list, assessing the efficiency of each solution and weighing when each is more suitable.

In this tutorial, you’ll learn how to use Python to count the number of words and word frequencies in both a string and a text file. Being able to count words and word frequencies is a useful skill. For example, knowing how to do this can be important in text classification machine learning algorithms.

By the end of this tutorial, you’ll have learned:

  • How to count the number of words in a string
  • How to count the number of words in a text file
  • How to calculate word frequencies using Python

Reading a Text File in Python

The processes to count words and calculate word frequencies shown below are the same for whether you’re considering a string or an entire text file. Because of this, this section will briefly describe how to read a text file in Python.

If you want a more in-depth guide on how to read a text file in Python, check out this tutorial here. Here is a quick piece of code that you can use to load the contents of a text file into a Python string:

# Reading a Text File in Python
file_path = '/Users/datagy/Desktop/sample_text.txt'

with open(file_path) as file:
    text = file.read()

I encourage you to check out the tutorial to learn why and how this approach works. However, if you’re in a hurry, just know that the process opens the file, reads its contents, and then closes the file again.

Count Number of Words In Python Using split()

One of the simplest ways to count the number of words in a Python string is by using the split() function. The split function looks like this:

# Understanding the split() function
str.split(
   sep=None     # The delimiter to split on
   maxsplit=-1  # The number of times to split
)

By default, Python will consider runs of consecutive whitespace to be a single separator. This means that if our string had multiple spaces, they’d only be considered a single delimiter. Let’s see what this method returns:

# Splitting a string with .split()
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(text.split())

# Returns: ['Welcome', 'to', 'datagy!', 'Here', 'you', 'will', 'learn', 'Python', 'and', 'data', 'science.']

We can see that the method now returns a list of items. Because we can use the len() function to count the number of items in a list, we’re able to generate a word count. Let’s see what this looks like:

# Counting words with .split()
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(len(text.split()))

# Returns: 11

Count Number of Words In Python Using Regex

Another simple way to count the number of words in a Python string is to use the regular expressions library, re. The library comes with a function, findall(), which lets you search for different patterns of strings.

Because we can use regular expression to search for patterns, we must first define our pattern. In this case, we want patterns of alphanumeric characters that are separated by whitespace.

For this, we can use the pattern w+, where w represents any alphanumeric character and the + denotes one or more occurrences. Once the pattern encounters whitespace, such as a space, it will stop the pattern there.

Let’s see how we can use this method to generate a word count using the regular expressions library, re:

# Counting words with regular expressions
import re
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(len(re.findall(r'w+', text)))

# Returns: 11

Calculating Word Frequencies in Python

In order to calculate word frequencies, we can use either the defaultdict class or the Counter class. Word frequencies represent how often a given word appears in a piece of text.

Using defaultdict To Calculate Word Frequencies in Python

Let’s see how we can use defaultdict to calculate word frequencies in Python. The defaultdict extend on the regular Python dictionary by providing helpful functions to initialize missing keys.

Because of this, we can loop over a piece of text and count the occurrences of each word. Let’s see how we can use it to create word frequencies for a given string:

# Creating word frequencies with defaultdict
from collections import defaultdict
import re

text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'

counts = defaultdict(int)
for word in re.findall('w+', text):
    counts[word] += 1

print(counts)

# Returns:
# defaultdict(<class 'int'>, {'welcome': 1, 'to': 1, 'datagy': 2, 'will': 1, 'teach': 1, 'data': 5, 'is': 1, 'fun': 1})

Let’s break down what we did here:

  1. We imported both the defaultdict function and the re library
  2. We loaded some text and instantiated a defaultdict using the int factory function
  3. We then looped over each word in the word list and added one for each time it occurred

Using Counter to Create Word Frequencies in Python

Another way to do this is to use the Counter class. The benefit of this approach is that we can even easily identify the most frequent word. Let’s see how we can use this approach:

# Creating word frequencies with Counter
from collections import Counter
import re

text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'
counts =  Counter(re.findall('w+', text))
print(counts)

# Returns:
# Counter({'data': 5, 'datagy': 2, 'welcome': 1, 'to': 1, 'will': 1, 'teach': 1, 'is': 1, 'fun': 1})

Let’s break down what we did here:

  1. We imported our required libraries and classes
  2. We passed the resulting list from the findall() function into the Counter class
  3. We printed the result of this class

One of the perks of this is that we can easily find the most common word by using the .most_common() function. The function returns a sorted list of tuples, ordering the items from most common to least common. Because of this, we can simply access the 0th index to find the most common word:

# Finding the Most Common Word
from collections import Counter
import re

text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'
counts =  Counter(re.findall('w+', text))
print(counts.most_common()[0])

# Returns:
# ('data', 5)

Conclusion

In this tutorial, you learned how to generate word counts and word frequencies using Python. You learned a number of different ways to count words including using the .split() method and the re library. Then, you learned different ways to generate word frequencies using defaultdict and Counter. Using the Counter method, you were able to find the most frequent word in a string.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • Python str.split() – Official Documentation
  • Python Defaultdict: Overview and Examples
  • Python: Count Number of Occurrences in List (6 Ways)
  • Python: Count Number of Occurrences in a String (4 Ways!)
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume, among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature’s God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the pursuit of Happiness. That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed, That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient causes; and accordingly all experience hath shown, that mankind are more disposed to suffer, while evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same Object evinces a design to reduce them under absolute Despotism, it is their right, it is their duty, to throw off such Government, and to provide new Guards for their future security. —Such has been the patient sufferance of these Colonies; and such is now the necessity which constrains them to alter their former Systems of Government. The history of the present King of Great Britain is a history of repeated injuries and usurpations, all having in direct object the establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid world. He has refused his Assent to Laws, the most wholesome and necessary for the public good. He has forbidden his Governors to pass Laws of immediate and pressing importance, unless suspended in their operation till his Assent should be obtained; and when so suspended, he has utterly neglected to attend to them. He has refused to pass other Laws for the accommodation of large districts of people, unless those people would relinquish the right of Representation in the Legislature, a right inestimable to them and formidable to tyrants only. He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their Public Records, for the sole purpose of fatiguing them into compliance with his measures. He has dissolved Representative Houses repeatedly, for opposing with manly firmness his invasions on the rights of the people. He has refused for a long time, after such dissolutions, to cause others to be elected; whereby the Legislative Powers, incapable of Annihilation, have returned to the People at large for their exercise; the State remaining in the mean time exposed to all the dangers of invasion from without, and convulsions within. He has endeavoured to prevent the population of these States; for that purpose obstructing the Laws of Naturalization of Foreigners; refusing to pass others to encourage their migration hither, and raising the conditions of new Appropriations of Lands. He has obstructed the Administration of Justice, by refusing his Assent to Laws for establishing Judiciary Powers. He has made judges dependent on his Will alone, for the tenure of their offices, and the amount and payment of their salaries. He has erected a multitude of New Offices, and sent hither swarms of Officers to harass our People, and eat out their substance. He has kept among us, in times of peace, Standing Armies without the Consent of our legislatures. He has affected to render the Military independent of and superior to the Civil Power. He has combined with others to subject us to a jurisdiction foreign to our constitution, and unacknowledged by our laws; giving his Assent to their Acts of pretended legislation: For quartering large bodies of armed troops among us: For protecting them, by a mock Trial, from Punishment for any Murders which they should commit on the Inhabitants of these States: For cutting off our Trade with all parts of the world: For imposing taxes on us without our Consent: For depriving us, in many cases, of the benefits of Trial by Jury: For transporting us beyond Seas to be tried for pretended offences: For abolishing the free System of English Laws in a neighbouring Province, establishing therein an Arbitrary government, and enlarging its Boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule into these Colonies: For taking away our Charters, abolishing our most valuable Laws, and altering fundamentally the Forms of our Governments: For suspending our own Legislatures, and declaring themselves invested with Power to legislate for us in all cases whatsoever. He has abdicated Government here, by declaring us out of his Protection and waging War against us. He has plundered our seas, ravaged our Coasts, burnt our towns, and destroyed the lives of our people. He is at this time transporting large armies of foreign mercenaries to compleat the works of death, desolation and tyranny, already begun with circumstances of Cruelty & perfidy scarcely paralleled in the most barbarous ages, and totally unworthy of the Head of a civilized nation. He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country, to become the executioners of their friends and Brethren, or to fall themselves by their Hands. He has excited domestic insurrections amongst us, and has endeavoured to bring on the inhabitants of our frontiers, the merciless Indian Savages, whose known rule of warfare, is an undistinguished destruction of all ages, sexes and conditions. In every stage of these Oppressions We have Petitioned for Redress in the most humble terms: Our repeated Petitions have been answered only by repeated injury. A Prince, whose character is thus marked by every act which may define a Tyrant, is unfit to be the ruler of a free People. Nor have We been wanting in attention to our Brittish brethren. We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpations, which would inevitably interrupt our connections and correspondence. They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our Separation, and hold them, as we hold the rest of mankind, Enemies in War, in Peace Friends. We, therefore, the Representatives of the United States of America, in General Congress, Assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions, do, in the Name, and by the Authority of the good People of these Colonies, solemnly publish and declare, That these United Colonies are, and of Right ought to be Free and Independent States; that they are Absolved from all Allegiance to the British Crown, and that all political connection between them and the State of Great Britain, is and ought to be totally dissolved; and that as Free and Independent States, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which Independent States may of right do. And for the support of this Declaration, with a firm reliance on the Protection of Divine Providence, we mutually pledge to each other our Lives, our Fortunes and our sacred Honor.

Python Count The Frequency Of Words In A List With Code Examples

Table of Contents Show

  • How do you count the frequency of a string in a list Python?
  • How do you count occurrences in a list in Python?
  • How do you count frequency in words?
  • How do you count occurrences of each word in a string in Python?
  • How do you count occurrences in a list?
  • How do you count repeated letters in Python?
  • How do you count repeated elements in a string Python?
  • How do you print the frequency of words in python?
  • How do you count occurrences of each word in a string?
  • How do you count the frequency of text values in a column?
  • Visualize Python code execution:
  • How to Count the Number of Occurrences in the List?
  • 1) Using count() method
  • 2) Using a loop
  • 3) Using countof() method
  • 4) Using counter() method
  • 5) Using pandas library
  • 6) Using loops and dict in python

We will use programming in this lesson to attempt to solve the Python Count The Frequency Of Words In A List puzzle. This is demonstrated by the following code.

from collections import Counter
list1=[‘apple’,’egg’,’apple’,’banana’,’egg’,’apple’]
counts = Counter(list1)
print(counts)
# Counter({‘apple’: 3, ‘egg’: 2, ‘banana’: 1})

As we have seen, the Python Count The Frequency Of Words In A List problem was solved by using a number of different instances.

How do you count the frequency of a string in a list Python?

We can use the counter() method from the collections module to count the frequency of elements in a list.20-Aug-2021

How do you count occurrences in a list in Python?

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.12-Nov-2021

How do you count frequency in words?

Approach: To solve the problem mentioned above we have to follow the steps given below:

  • Use a Map data structure to store the occurrence of each word in the string.
  • Traverse the entire string and check whether the current word is present in map or not.
  • Traverse in the map and print the frequency of each word.

How do you count occurrences of each word in a string in Python?

Python Code: def word_count(str): counts = dict() words = str. split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count(‘the quick brown fox jumps over the lazy dog. ‘))19-Aug-2022

How do you count occurrences in a list?

Using the count() Function The «standard» way (no external libraries) to get the count of word occurrences in a list is by using the list object’s count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.28-Dec-2021

How do you count repeated letters in Python?

Python

  • string = «Great responsibility»;
  • print(«Duplicate characters in a given string: «);
  • #Counts each character present in the string.
  • for i in range(0, len(string)):
  • count = 1;
  • for j in range(i+1, len(string)):
  • if(string[i] == string[j] and string[i] != ‘ ‘):
  • count = count + 1;

How do you count repeated elements in a string Python?

Step 1: Declare a String and store it in a variable. Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1. Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.

How do you print the frequency of words in python?

Using FreqDist() The natural language tool kit provides the FreqDist function which shows the number of words in the string as well as the number of distinct words. Applying the most_common() gives us the frequency of each word.20-Dec-2019

How do you count occurrences of each word in a string?

Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.27-Jul-2022

How do you count the frequency of text values in a column?

You can use the COUNTIF(range, criteria) function to count how often specific text occurs in an Excel column.02-Sept-2021

Last update on August 19 2022 21:51:42 (UTC/GMT +8 hours)

Write a Python program to count the occurrences of each word in a given sentence.

Python count word occurrences in list

Sample Solution:-

Python Code:

def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count(‘the quick brown fox jumps over the lazy dog.’))

Sample Output:

{‘the’: 2, ‘jumps’: 1, ‘brown’: 1, ‘lazy’: 1, ‘fox’: 1, ‘over’: 1, ‘quick’: 1, ‘dog.’: 1}

Flowchart:

Python count word occurrences in list

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove the characters which have odd index values of a given string.
Next: Write a Python script that takes input from the user and displays that input back in upper and lower cases.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.



Anti-gravity:

import antigravity
antigravity.fly()

  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution — JOINS
  • SQL Exercises, Practice, Solution — SUBQUERIES
  • JavaScript basic — Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database — SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary — Exercises, Practice, Solution
  • Python Programming Puzzles — Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops — Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda — Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation

Python is well known for its easy syntax, fast implementation, and, most importantly, large support of multiple data structures. Lists are one of those data structures in python which helps to store large amounts of sequential data in a single variable. As huge data is stored under the same variable, it is sometimes quite difficult to manually identify whether the given element is present in the lists, and if yes, how many times. Therefore, in this article, we will study the various ways to count the number of occurrences in the list in python. To recall the concepts of python lists in detail, visit our article “3 Ways to Convert List to Tuple”. 

How to Count the Number of Occurrences in the List?

There are six ways by which you can count the number of occurrences of the element in the list. Let us study them all in brief below:

1) Using count() method

count() is the in-built function by which python count occurrences in list. It is the easiest among all other methods used to count the occurrence. Count() methods take one argument, i.e., the element for which the number of occurrences is to be counted.

For example:

sample_list = [«a», «ab», «a», «abc», «ab», «ab»] print(sample_list.count(«a»)) print(sample_list.count(«ab»))

Output

2) Using a loop

Another simple approach to counting the occurrence is by using a loop with the counter variable. Here, the counter variable keeps increasing its value by one each time after traversing through the given element. At last, the value of the counter variable displays the number of occurrences of the element.

For example:

def countElement(sample_list, element): return sample_list.count(element) sample_list = [«a», «ab», «a», «abc», «ab», «ab»] element = «ab» print({} has occurred {} times.format(element, countElement(sample_list, element)))

Output

3) Using countof() method

Operator module from python library consists of countof() method which helps to return the number of occurrence of the element from the lists. This method takes two arguments, i.e., the list in which the count needs to be performed and the element which needs to be found. Moreover, you have to import the operator module before beginning the program using the “import” keyword as shown below:

For example:

sample_list = [«a», «ab», «a», «abc», «ab», «ab»] import operator as op print(op.countOf(sample_list,«a»))

Output

4) Using counter() method

Python possesses an in-built module named collections, including multiple methods to ease your programming. One such method is a counter() method where elements are stored as a dictionary with keys and counts as values.

Therefore, the counter() method helps you return the total number of occurrences of a given element inside the given list by taking one parameter as the list in which the element is to be counted. Remember that you have to import the collections module to use the counter() method as shown in the below example:

For example:

sample_list = [«a», «ab», «a», «abc», «ab», «ab»] from collections import Counter print(Counter(sample_list)) c = Counter(sample_list) print(c[«a»])

Output

Counter({‘ab’: 3, ‘a’: 2, ‘abc’: 1}) 2

5) Using pandas library

Pandas is the in-built python library, highly popular for data analysis and data manipulation. It is an open-source tool with a large range of features and is widely used in the domains like machine learning and artificial intelligence. To learn more about pandas, please visit our article “Numpy vs Pandas.”

Pandas possess a wide range of default methods, one of which is the value_count() method. Along with the value_count() method, pandas use series, i.e., a one-dimensional array with axis label.

To count the occurrence of elements using pandas, you have to convert the given list into the series and then use the value_count() method, which returns the object in descending order. By these, you can easily note that the first element is always the most frequently occurring element.

Check out the below example for a better understanding of the Pandas library

For example:

import pandas as pd sample_list = [«a», «ab», «a», «abc», «ab», «ab»] count = pd.Series(sample_list).value_counts() print(count[«a»])

Output

6) Using loops and dict in python

This is the most traditional method by which python count occurrences in the list that is by using the loop, conditional statement, and dictionaries. By this method, you have to create the empty dictionary and then iterate over the list. Later, check if the element present in the list is available in the dictionary or not. If yes, then increase its value by one; otherwise, introduce a new element in the dictionary and assign 1 to it. Repeat the same process until all the elements in the lists are visited.

Remember that this method is quite different from the previous method using the loop and the counter variable. The early mentioned method does not make use of dictionary data structure, whereas this one does. At last, print the count of occurrence of each element as shown in the below example:

For example:

sample_list = [«a», «ab», «a», «abc», «ab», «ab»] def countOccurrence(a): k = {} for j in a: if j in k: k[j] +=1 else: k[j] =1 return k
print(countOccurrence(sample_list))

Output

{‘a’: 2, ‘ab’: 3, ‘abc’: 1}

Conclusion

Programming is all about reducing manual tasks and shifting to automation. Counting the occurrence of elements from the large dataset manually is quite a tedious and time-consuming task. Therefore, python provides various methods by which you can count the occurrence of elements easily and quickly with few lines of code, just like shown in the article above. It is recommended to learn and understand all these methods to make your programming effective and efficient.

Понравилась статья? Поделить с друзьями:
  • Count values in column in excel
  • Count unique words in word
  • Count unique in excel column
  • Count the unique values in excel
  • Count the numbers in excel