Поиск по сайту:

Программа Python для подсчета слов с определенной буквой


В этой статье мы научимся подсчитывать слова с определенной буквой в строке в Python.

Используемые методы

Ниже приведены различные методы выполнения этой задачи:

  • Использование понимания списка, функций len() и Split().

  • Использование функций Split() и find()

  • Использование функций Split(), replace() и len().

  • Использование функции Счетчик()

Пример

Предположим, мы взяли входную строку и некоторый случайный символ. Теперь мы посчитаем слова, содержащие данный входной символ, во входной строке.

Вход

inputString = 'hello tutorialspoint python codes'
inputChar = "p"

Выход

Count of words containing the char 'p' is: 2

В приведенной выше строке слова, содержащие входной символ «p», — это tutorialspoint , python. Следовательно, выход равен 2.

Метод 1: использование понимания списка, функций len() и Split().

Понимание списка

Если вы хотите создать новый список на основе значений существующего списка, понимание списка обеспечивает более короткий/лаконичный синтаксис.

len() — количество элементов в объекте возвращается методом len(). Функция len() возвращает количество символов в строке, если объект является строкой.

split() — разбивает строку на список. Мы можем определить разделитель; разделителем по умолчанию является любой пробел.

Алгоритм (шаги)

Ниже приводится алгоритм/шаги, которые необходимо выполнить для выполнения желаемой задачи.

  • Создайте переменную для хранения входной строки.

  • Распечатайте входной список.

  • Создайте еще одну переменную для хранения входного символа.

  • Используйте функцию Split(), чтобы разделить входную строку на список слов и пройти по этому списку, а затем проверить, присутствует ли входной символ в текущем элементе списка.

  • Выведите количество слов, содержащих данный входной символ во входной строке.

Пример

Следующая программа возвращает количество слов с заданным входным символом во входной строке, используя понимание списка, функции len() и Split():

# input string
inputString = 'hello tutorialspoint python codes'

# printing input string
print("Input String:", inputString)

# input character
inputChar = "p"

# splitting the input string into a list of words and traversing in that list

# and then checking if the input char is present in the current list element
wordsCount = len([element for element in inputString.split() if inputChar in element])

# printing the count of words containing the input character
print("The Count of words containing the char 'p' is:", wordsCount)

Выход

При выполнении вышеуказанная программа сгенерирует следующий вывод:

Input String: hello tutorialspoint python codes
The count of words containing the char 'p' is: 2

Способ 2. Использование функций Split() и find().

Метод find() – находит первое вхождение заданного значения. Этот метод возвращает -1, если значение не найдено.

Синтаксис

string.find(value, start, end)

Пример

Следующая программа возвращает количество слов с заданным входным символом во входной строке, используя функции Split() и find():

# input string
inputString = 'hello tutorialspoint python codes'

# printing input string
print("Input String:", inputString)

# input character
inputChar = "p"

# storing the words count with the input character
wordsCount=0

# splitting input string into the list of words
wordsList= inputString.split()

# traversing in that words list
for element in wordsList:
   
   # checking whether input char is present in the current list element
   if(element.find(inputChar)!=-1):
      
      # incrementing word count value by 1 if the condition is true
      wordsCount+=1
print("The Count of words containing the char 'p' is:", wordsCount)

Выход

При выполнении вышеуказанная программа сгенерирует следующий вывод:

Input String: hello tutorialspoint python codes
The count of words containing the char 'p' is: 2

Способ 3. Использование функций Split(), replace() и len().

функция replace() — возвращает копию строки, которая заменяет все вхождения старой подстроки другой новой подстрокой.

Синтаксис

string.replace(old, new, count)

Пример

Следующая программа возвращает количество слов с заданным входным символом во входной строке, используя функции Split(), replace() и len():

# input string
inputString = 'hello tutorialspoint python codes'

# printing input string
print("Input String:", inputString)

# input character
inputChar = "p"

# storing the words count with the input character
wordsCount=0

# splitting input string into the list of words
wordsList= inputString.split()

# traversing in that words list
for element in wordsList:

   # replacing given input char with space and storing that string
   p = element.replace(inputChar, "")

   # incrementing the words count by 1 if the length of the above string # is less than the length of the current element
   if(len(p) < len(element)):
      wordsCount += 1
print("The Count of words containing the char 'p' is:", wordsCount)

Выход

Input String: hello tutorialspoint python codes
The count of words containing the char 'p' is: 2

Способ 4: использование функции Counter()

Функция Counter() — подкласс, который подсчитывает хэшируемые объекты. Он неявно создает хеш-таблицу итерируемого объекта при вызове/вызове.

В этом методе функция Counter() возвращает частоту символов каждого слова во входной строке.

Пример

Следующая программа возвращает количество слов с заданным входным символом во входной строке с помощью функции Counter():

# importing a Counter function from the collections module
from collections import Counter

# input string
inputString = 'hello tutorialspoint python codes'

# printing input string
print("Input String:", inputString)

# input character
inputChar = "p"

# storing the words count with the input character
wordsCount = 0

# splitting input string into the list of words
wordsList = inputString.split()

# traversing through the elements of the words list
for element in wordsList:
   
   # getting the frequency of characters of the current word as a key-value pair
   ele_frequency = Counter(element)
   
   # checking whether the input char is present in the keys of the frequency dictionary
   if inputChar in ele_frequency.keys():
      
      # incrementing the words count by 1 if the condition is true
      wordsCount += 1
print("The Count of words containing the char 'p' is:", wordsCount)

Выход

Input String: hello tutorialspoint python codes
The count of words containing the char 'p' is: 2

Заключение

В этой статье мы изучили 4 разных способа подсчета слов, начинающихся с определенной буквы. Мы также узнали, как использовать функцию Counter() для получения частоты повторяющихся элементов (хеширование по словарю).

Статьи по данной тематике: