You can download this code by clicking the button below.
This code is now available for download.
This function uses the Word2Vec model from the gensim library to generate a random sentence containing specified seed words. It first loads a pre-trained Word2Vec model from gensim's downloader, then finds the words most similar to the seed words using this model, and finally combines these words into a sentence.
Technology Stack : gensim
Code Type : Generate random sentences
Code Difficulty : Intermediate
def generate_random_sentence(text_model, seed_words, num_words=5):
import gensim.downloader as api
from gensim.models import Word2Vec
# Download a pre-trained Word2Vec model
model = api.load("glove-wiki-gigaword-100")
# Generate a random sentence using the Word2Vec model
random_sentence = model.wv.most_similar(seed_words=seed_words, topn=num_words)
return " ".join([word for word, _ in random_sentence])