список ассоциаций фраз и изображений

у нас есть файл txt с базой фраз
нужно сделать программу которая бы отвечала на фразу ввода input случайной фразой
из базы в которой есть 1-3 похожих слов ( с одним корнем )
далее программа выводит случайное изображение jpg из папки "фото"
и спрашивает подходит ли это изображение к нашей фразе
если мы отвечаем - да то программа запоминает эти ассоциации фото и фраз
и делает что то вроде списка  ( набор фраз -> фото )
который потом можно будет воспроизвести
если ответ - нет то начинаем ввод новой фразы input через цикл while


 **


It seems like you want to create a program that responds to user input phrases with a random phrase from a database that has 1-3 similar words (with the same root) and then displays a random image from a "фото" folder. The program should ask if the image matches the phrase, and if the user responds with "yes", it should remember the association between the phrase and the image. If the user responds with "no", the program should start a new cycle of input and response.

Here's a possible implementation of this program in Python:

Step 1: Load the phrase database

We can load the phrase database from the txt file into a list of phrases. We can use the readlines() method to read the file line by line and store each line as a phrase in the list.


with open('phrases.txt', 'r') as f:
    phrases = [line.strip() for line in f.readlines()]


Step 2: Find similar phrases

We can use the nltk library to find phrases with 1-3 similar words (with the same root). We can tokenize each phrase and find the root of each word using the WordNetLemmatizer.

import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

def find_similar_phrases(input_phrase):
    input_tokens = word_tokenize(input_phrase)
    input_roots = [lemmatizer.lemmatize(token) for token in input_tokens]
    similar_phrases = []
    for phrase in phrases:
        phrase_tokens = word_tokenize(phrase)
        phrase_roots = [lemmatizer.lemmatize(token) for token in phrase_tokens]
        common_roots = set(input_roots) & set(phrase_roots)
        if 1 <= len(common_roots) <= 3:
            similar_phrases.append(phrase)
    return similar_phrases
Step 3: Display a random image

We can use the os and random libraries to select a random image from the "фото" folder.

import os
import random

def display_random_image():
    image_folder = 'фото'
    image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg')]
    random_image = random.choice(image_files)
    print(f'Displaying image: {random_image}')
    # Display the image using a library like Pillow or Matplotlib
Step 4: Ask for user input and remember associations

We can use a dictionary to store the associations between phrases and images. We can ask the user if the image matches the phrase, and if they respond with "yes", we can add the association to the dictionary.

associations = {}

while True:
    input_phrase = input('Enter a phrase: ')
    similar_phrases = find_similar_phrases(input_phrase)
    if similar_phrases:
        random_phrase = random.choice(similar_phrases)
        print(f'Response: {random_phrase}')
        display_random_image()
        response = input('Does the image match the phrase? (yes/no): ')
        if response.lower() == 'yes':
            associations[random_phrase] = random_image
            print(f'Association remembered: {random_phrase} -> {random_image}')
        else:
            print('Starting a new cycle...')
    else:
        print('No similar phrases found. Starting a new cycle...')
This is a basic implementation of the program. You can modify it to fit your specific needs and add more features as required.

Do you want me to elaborate on any part of this implementation?

сделай из этого один код


@ Here is the complete code:



 **


import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
import os
import random

# Load the phrase database
with open('phrases.txt', 'r') as f:
    phrases = [line.strip() for line in f.readlines()]

# Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()

# Function to find similar phrases
def find_similar_phrases(input_phrase):
    input_tokens = word_tokenize(input_phrase)
    input_roots = [lemmatizer.lemmatize(token) for token in input_tokens]
    similar_phrases = []
    for phrase in phrases:
        phrase_tokens = word_tokenize(phrase)
        phrase_roots = [lemmatizer.lemmatize(token) for token in phrase_tokens]
        common_roots = set(input_roots) & set(phrase_roots)
        if 1 <= len(common_roots) <= 3:
            similar_phrases.append(phrase)
    return similar_phrases

# Function to display a random image
def display_random_image():
    image_folder = 'фото'
    image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg')]
    random_image = random.choice(image_files)
    print(f'Displaying image: {random_image}')
    # Display the image using a library like Pillow or Matplotlib

# Initialize the associations dictionary
associations = {}

# Main loop
while True:
    input_phrase = input('Enter a phrase: ')
    similar_phrases = find_similar_phrases(input_phrase)
    if similar_phrases:
        random_phrase = random.choice(similar_phrases)
        print(f'Response: {random_phrase}')
        display_random_image()
        response = input('Does the image match the phrase? (yes/no): ')
        if response.lower() == 'yes':
            associations[random_phrase] = random_image
            print(f'Association remembered: {random_phrase} -> {random_image}')
        else:
            print('Starting a new cycle...')
    else:
        print('No similar phrases found. Starting a new cycle...')




Please note that you need to download the nltk data by running nltk.download('punkt') and nltk.download('wordnet') in your Python environment before running this code. Also, you need to have the phrases.txt file in the same directory as the script, and the фото folder with the images.

Let me know if you have any questions or need further modifications!


Рецензии