Примеры кода Python: подсчет, замена и генерация словосочетаний

Фраза «Бетти Боттер купила немного программы на Python с маслом» кажется предложением, намеренно составленным с использованием аллитераций и игры слов. В английском языке оно не имеет конкретного значения или цели. Однако я могу предоставить вам несколько примеров кода Python и методов, связанных с обработкой масла или текста.

Вот несколько примеров:

  1. Подсчет появления определенного слова в тексте:

    def count_word_occurrence(text, word):
    words = text.lower().split()
    count = words.count(word.lower())
    return count
    text = "Betty Botter bought some butter, but the butter was bitter."
    word = "butter"
    occurrence = count_word_occurrence(text, word)
    print(f"The word '{word}' occurs {occurrence} time(s) in the text.")
  2. Замена слова в тексте:

    def replace_word(text, old_word, new_word):
    return text.replace(old_word, new_word)
    text = "Betty Botter bought some butter, but the butter was bitter."
    old_word = "bitter"
    new_word = "delicious"
    updated_text = replace_word(text, old_word, new_word)
    print(updated_text)
  3. Генерация всех возможных комбинаций слов из заданного текста:

    from itertools import combinations
    def generate_word_combinations(text):
    words = text.split()
    combinations_list = []
    for r in range(1, len(words) + 1):
        combinations_list.extend(combinations(words, r))
    return combinations_list
    text = "Betty Botter bought some butter."
    combinations = generate_word_combinations(text)
    print(combinations)