Sunday, December 29, 2024
Google search engine
HomeLanguagesPython – Count of Words with specific letter

Python – Count of Words with specific letter

Given a string of words, extract the count of words with a specific letters.

Input : test_str = ‘neveropen is best for Lazyroar’, letter = “g” 
Output : 2 
Explanation : “g” occurs in 2 words. 

Input : test_str = ‘neveropen is best for Lazyroar’, letter = “s” 
Output : 4
Explanation : “s” occurs in 4 words.

Method #1 : Using list comprehension + len() + split()

This is one of the ways in which this task can be performed. In this, we perform task of extracting words from string using split() and loop is used to iterate words to check for letter existence of letter and len() is used to fetch the number of words with letter.

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using list comprehension + len() + split()
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting desired count using len()
# list comprehension is used as shorthand
res = len([ele for ele in test_str.split() if letter in ele])
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(n)

Auxiliary Space: O(1)

Method #2 : Using filter() + lambda + len() + split()

This is yet another way in which this task can be performed. In this, we perform the task of filtering using filter() + lambda.

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using filter() + lambda + len() + split()
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting desired count using len()
# filter() used to check for letter existence
res = len(list(filter(lambda ele : letter in ele, test_str.split())))
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(n)

Auxiliary Space: O(1)

Method #3 : Using len() + for loop

We use len() and for loop to iterate over the string to solve the problem.

Python3




# Python3 code to get count of Words with specific letter
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
""" As we have to only count one letter per word we have to
    check if we have checked that word or not and to do so
    we use variable word_count that become odd if we founded the letter
    in the word and even when not"""
word_count = 0
 
# count of words with specific letter
word = 0
 
# For loop to iterate over string
for i in range(len(test_str)):
    if word_count % 2 == 0 and test_str[i] == letter:
        word += 1
        word_count = 1
        # set word_count an odd number so we know to not check the current word.
    elif test_str[i] == " ":
        """    New word starts with " "  """
        word_count = 0
        # set word_count an even number so we know to check the current word.
print("Words count :", word)
# This code is contributed by Shivesh Kumar Dwivedi


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(n)

Auxiliary Space: O(1)

Method #4 : Using split() and find()

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using split() and find()
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting words with specific letter
res=0
x=test_str.split()
for i in x:
    if(i.find(letter)!=-1):
        res+=1
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #5 : Using split(),replace() and len() methods

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting words with specific letter
res = 0
x = test_str.split()
for i in x:
    a = i.replace(letter, "")
    if(len(a) < len(i)):
        res += 1
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

The Time and Space Complexity for all the methods are the same
Time Complexity: O(n)
Auxiliary Space: O(n)

Method #6: Using Counter() function

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
from collections import Counter
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting words with specific letter
res = 0
x = test_str.split()
for i in x:
    freq = Counter(i)
    if letter in freq.keys():
        res += 1
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #7: Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
import operator as op
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting words with specific letter
res = 0
x = test_str.split()
for i in x:
    if op.countOf(i, letter) > 0:
        res += 1
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(N)
Auxiliary Space : O(N)

Method #8 : Using split() and set(): 

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using set + split()
# initializing string
test_str = 'neveropen is best for Lazyroar'
# printing original string
print("The original string is : " + str(test_str))
# initializing letter
letter = "e"
# Convert the input string to a set of unique words
words = set(test_str.split())
# Initialize count to keep track of the number of words that contain the specific letter
count = 0
# Iterate over the unique words in the set
for word in words:
   # Check if the specific letter is in the current word
   if letter in word:
       # If the letter is found, increment the count
       count +=1
# printing result
print("Words count : " + str(count))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity: O(N)
Space Complexity : O(1)

Method#9: Using Recursion method.

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using recursive method
def count_words_with_letter(string, letter, count=0):
    if not string:
        return count
    if letter in string.split()[0]:
        count += 1
    return count_words_with_letter(string[len(string.split()[0]) + 1:], letter, count)
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
# printing original string
print("The original string is : " + str(test_str))
# initializing letter
letter = "e"
result = count_words_with_letter(test_str, letter)
# printing result
print("Words count:", result)
#this code contributed by tvsk


Output

The original string is : neveropen is best for Lazyroar
Words count: 3

Time Complexity: O(n)

Auxiliary Space: O(1)

Method #10 : Using re module
This approach uses the re (regular expression) module in python to find all occurrences of the given letter in the string and counting the number of matches.

Python3




import re
 
def count_words_with_letter(test_str, letter):
    # Split the string into words
    words = test_str.split()
     
    # Use re.match to check if the specified letter is present in each word
    count = sum([1 for word in words if re.match(f'.*{letter}.*', word)])
     
    return count
 
# Test the function with the example inputs
test_str = 'neveropen is best for Lazyroar'
letter = 'e'
 
print(count_words_with_letter(test_str, letter))


Output

3

Time Complexity: O(n * m), where n is the number of words in the input string and m is the length of each word on average. This is because the re.match function performs a search operation on each word in the input string, and the length of each search operation is proportional to the length of the word.

Auxiliary Space: O(1)

Method #11 : Using operator.contains() method

Approach 

  1. Split the string and it turns to list
  2. Initiated a for loop to traverse the list
  3. Checked whether the letter is present in each element of list using operator.contains()
  4. If yes increment the result variable
  5. Display the result variable

Python3




# Python3 code to demonstrate working of
# Count of Words with specific letter
# Using split() and find()
 
# initializing string
test_str = 'neveropen is best for Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing letter
letter = "e"
 
# extracting words with specific letter
res=0
x=test_str.split()
import operator
for i in x:
    if(operator.contains(i,letter)):
        res+=1
 
# printing result
print("Words count : " + str(res))


Output

The original string is : neveropen is best for Lazyroar
Words count : 3

Time Complexity : O(N)

Auxiliary Space : O(1)

RELATED ARTICLES

Most Popular

Recent Comments