рифмо- бот

import random

def load_lines(filename):
    """Загрузить строки из файла."""
    with open(filename, 'r', encoding='utf-8') as file:
        return [line.strip() for line in file.readlines()]

def save_line(filename, line):
    """Сохранить новую строку в файл."""
    with open(filename, 'a', encoding='utf-8') as file:
        file.write(line + '\n')

def find_rhymes(input_line, lines):
    """Найти рифмующиеся строки с приоритетом уникальных."""
    input_word = input_line.split()[-1]  # Последнее слово
    input_suffix = input_word[-3:]  # Последние 3 буквы слова
    # Рифмы из двух букв
    suffix_12 = input_word[-3:-1]  # 12 (вторая и третья буквы)
    suffix_23 = input_word[-2:]     # 23 (последние две буквы)

    # Создаем список для рифм
    rhymes = []

    # Проверяем каждую строку в lines
    for line in lines:
        if line != input_line and (line.endswith(input_suffix) or line.endswith(suffix_12) or line.endswith(suffix_23)):
            rhymes.append(line)  # Добавляем в список рифм

    # Убираем повторы и выбираем уникальные рифмы
    unique_rhymes = list(set(rhymes))
    n = 4  #   число выводимых строк бота
    # Если уникальных рифм недостаточно
    if len(unique_rhymes) < n:
        additional_rhymes = list(set(rhymes) - set(unique_rhymes))
        unique_rhymes.extend(additional_rhymes)

    # Убираем повторы и выбираем случайные строки
    unique_rhymes = list(set(unique_rhymes))
    return random.sample(unique_rhymes, min(n, len(unique_rhymes))) if unique_rhymes else []

def main():
    filename = 'строки-бота.txt'
    lines = load_lines(filename)

    while True:
        input_line = input("ввод: ")
        if input_line.lower() == 'выход':
            break

        rhymes = find_rhymes(input_line, lines)

        if rhymes:
            for rhyme in rhymes:
                print(rhyme)
        else:
            print("Рифмы не найдены.")

        # Добавляем новую строку в файл
        save_line(filename, input_line)

if __name__ == "__main__":
    main()






 обучение бота ->





import numpy as np
import re
import pickle
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from collections import defaultdict

class SimpleDialogueTransformer:
    def __init__(self, model_path='dialogue_model.pkl'):
        self.model_path = model_path
        self.vectorizer = TfidfVectorizer(ngram_range=(1, 3))
        self.dialogue_pairs = []
        self.semantic_groups = defaultdict(set)
        self.phrase_vectors = None
        self.known_phrases = []

        # Загружаем модель, если она существует
        if os.path.exists(model_path):
            self.load_model()
       
    def preprocess_text(self, text):
        """Предобработка текста: приведение к нижнему регистру, удаление спец. символов"""
        return re.sub(r'[^\w\s]', '', text.lower())
   
    def extract_semantic_groups(self, text):
        """Извлечение семантических групп из текста"""
        words = self.preprocess_text(text).split()
        for i in range(len(words) - 1):
           # Добавляем до двух следующих слов
   
    def update_vectors(self):
        """Обновление векторных представлений фраз"""
        if self.known_phrases:
            self.phrase_vectors = self.vectorizer.fit_transform(self.known_phrases)
   
    def find_similar_phrase(self, input_text):
        """Поиск наиболее похожей фразы из известных"""
        if not self.known_phrases:
            return None, 0
            
        input_vector = self.vectorizer.transform([input_text])
        similarities = cosine_similarity(input_vector, self.phrase_vectors)[0]
       
        if np.max(similarities) > 0.7:  # Порог схожести
            most_similar_idx = np.argmax(similarities)
            return self.known_phrases[most_similar_idx], similarities[most_similar_idx]
       
        return None, 0
   
    def learn(self, user_input, response):
        """Обучение модели на новой паре диалога"""
        processed_input = self.preprocess_text(user_input)
        processed_response = self.preprocess_text(response)
       
        self.dialogue_pairs.append((processed_input, processed_response))
       
        if processed_input not in self.known_phrases:
            self.known_phrases.append(processed_input)
       
        self.extract_semantic_groups(processed_input)
        self.extract_semantic_groups(processed_response)
        self.update_vectors()
        self.save_model()
   
    def generate_response(self, user_input):
        """Генерация ответа на основе известных диалогов и семантики"""
        processed_input = self.preprocess_text(user_input)
        similar_phrase, similarity = self.find_similar_phrase(processed_input)
       
        if similar_phrase:
            for inp, resp in self.dialogue_pairs:
                if inp == similar_phrase:
                return f"Ответ (схожесть {similarity:.2f}): {resp}"
       
        response_parts = []
        for word in processed_input.split():
            if word in self.semantic_groups:
                related_words = list(self.semantic_groups[word])
                if related_words:
                response_parts.append(np.random.choice(related_words))
       
        return "-> " + " ".join(response_parts) if response_parts else "Я не знаю, как ответить. Научите меня, пожалуйста."
   
    def save_model(self):
        """Сохранение модели"""
        with open(self.model_path, 'wb') as f:
            pickle.dump({
                'dialogue_pairs': self.dialogue_pairs,
                'semantic_groups': self.semantic_groups,
                'known_phrases': self.known_phrases,
                'vectorizer': self.vectorizer
            }, f)
   
    def load_model(self):
        """Загрузка модели"""
        with open(self.model_path, 'rb') as f:
            data = pickle.load(f)
            self.dialogue_pairs = data['dialogue_pairs']
            self.semantic_groups = data['semantic_groups']
            self.known_phrases = data['known_phrases']
            self.vectorizer = data['vectorizer']
       
        self.phrase_vectors = self.vectorizer.transform(self.known_phrases) if self.known_phrases else None

# Пример использования модели
def main():
    bot = SimpleDialogueTransformer()
   
    print("Привет! Я бот, который учится в процессе общения.")
   
    while True:
        user_input = input("\nВы: ")

        if user_input.lower() == 'выход':
            print("До свидания!")
            break
       
        response = bot.generate_response(user_input)
        print(f"Бот: {response}")
       
        if "Я это не знаю" in response or "->" in response:
            correct_response = input("Как мне ответить? ")
            bot.learn(user_input, correct_response)
            print("Спасибо, я запомнил!")

if __name__ == "__main__":
    main()








 поиск рифм в файле ->




def get_last_word(s):
    return s.split()[-1] if s.split() else ""

def check_conditions(s1, s2):
    last_word1 = get_last_word(s1)
    last_word2 = get_last_word(s2)
   
    # Проверяем, чтобы последние слова не совпадали
    if last_word1 == last_word2:
        return False

    # Проверяем совпадение двух последних или двух предпоследних букв
    if (s1[-2:] == s2[-2:] or s1[-3:-1] == s2[-3:-1]):
        return True
   
    return False

def find_matching_pairs(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    pairs = []
    for i in range(len(lines)):
        for j in range(i + 1, len(lines)):
            if check_conditions(lines[i].strip(), lines[j].strip()):
                pairs.append((lines[i].strip(), lines[j].strip()))

    return pairs

def main():
    filename = 'строки.txt' 
    pairs = find_matching_pairs(filename)

    for line1, line2 in pairs:
        print(line1)
        print(line2)
        print()  # Пустая строка для разделения пар

if __name__ == "__main__":
    main()


Рецензии