given this code, how can i reduce the number of total word produced? for example, i…
- User
given this code, how can i reduce the number of total word produced? for example, i would like to obtain less words from the clustered part.
import csv import re import os import nltk import pandas as pd from collections import defaultdict, Counter from nltk.stem import WordNetLemmatizer from gensim.models import KeyedVectors, FastText from sklearn.cluster import KMeans import numpy as np
------------------------------#
Setup
------------------------------#
Download NLTK data files (only need to run once)
nltk.download('wordnet')
nltk.download('omw-1.4')
Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()
Function to load the appropriate word embedding model
def load_model(model_type, model_path): if model_type == 'word2vec': print("Loading Word2Vec model. This may take a few minutes...") model = KeyedVectors.load_word2vec_format(model_path, binary=True) print("Word2Vec model loaded successfully.") elif model_type == 'glove': print("Loading GloVe model. This may take a few minutes...") model = {} with open(model_path, 'r', encoding='utf-8') as f: for line in f: values = line.split() word = values[0] vector = np.asarray(values[1:], dtype='float32') model[word] = vector print("GloVe model loaded successfully.") elif model_type == 'fasttext': print("Loading FastText model. This may take a few minutes...") model = FastText.load_fasttext_format(model_path) print("FastText model loaded successfully.") else: raise ValueError(f"Unsupported model type: {model_type}") return model
Function to get the vector for a word/phrase
def get_word_vector(word, model, model_type): if model_type in ['word2vec', 'fasttext']: if word in model: return model[word] elif model_type == 'glove': if word in model: return model[word] # Handle multi-word phrases by averaging their word vectors words = word.split() vectors = [] for w in words: if model_type in ['word2vec', 'fasttext'] and w in model: vectors.append(model[w]) elif model_type == 'glove' and w in model: vectors.append(model[w]) if vectors: return np.mean(vectors, axis=0) else: return None
Function to lemmatize a keyword
def lemmatize_keyword(keyword): return lemmatizer.lemmatize(keyword.lower())
Function to process the CSV file and lemmatize keywords per row, and output lemmatized counts
def lemmatize_keywords(input_file, lemmatized_counts_output_file): # Read the CSV file using pandas df = pd.read_csv(input_file)
code - Assistant