Вот фрагмент кода Python, который подсчитывает вхождения слова в заданной строке и печатает результат:
def count_word_occurrences(string, word):
# Split the string into words
words = string.split()
# Initialize a counter variable
count = 0
# Iterate over the words and count occurrences
for w in words:
if w == word:
count += 1
# Print the result
print(f"The word '{word}' appears {count} times in the string.")
# Example usage
string = "This is a sample string. It is a simple string."
word = "string"
count_word_occurrences(string, word)
Этот код определяет функцию count_word_occurrences, которая принимает два параметра: string(входная строка) и word(слово, которое нужно посчитать).. Он разбивает входную строку на отдельные слова с помощью метода split(), а затем перебирает каждое слово, сравнивая его с целевым словом. Если совпадение найдено, счетчик увеличивается. Наконец, функция печатает результат.
Вот еще несколько способов добиться того же результата:
Метод 1: использование метода count()
def count_word_occurrences(string, word):
count = string.count(word)
print(f"The word '{word}' appears {count} times in the string.")
Метод 2. Использование списка
def count_word_occurrences(string, word):
words = string.split()
count = sum(1 for w in words if w == word)
print(f"The word '{word}' appears {count} times in the string.")
Метод 3. Использование модуля reдля регулярных выражений
import re
def count_word_occurrences(string, word):
count = len(re.findall(r'\b' + word + r'\b', string))
print(f"The word '{word}' appears {count} times in the string.")