如何用Python获取西班牙语单词‘contador’的同义词列表?
Got it, let's solve this! Since standard WordNet doesn't handle Spanish, we need to use multilingual or Spanish-specific lexical tools. Here are two straightforward, reliable approaches:
Method 1: Use NLTK with Open Multilingual Wordnet (OMW)
The Open Multilingual Wordnet is an extension that adds support for dozens of languages, including Spanish. It's easy to set up with NLTK:
First, install NLTK if you haven't:
pip install nltkThen, write a Python script to download the OMW data and extract synonyms:
import nltk from nltk.corpus import wordnet as wn # Download the Open Multilingual Wordnet data nltk.download('omw-1.4') def get_spanish_synonyms(word): synonyms = set() # Get all synsets for the word in Spanish (lang='es') synsets = wn.synsets(word, lang='es') for synset in synsets: # Extract all Spanish lemmas from the synset for lemma in synset.lemmas(lang='es'): synonyms.add(lemma.name()) # Convert to a sorted list return sorted(synonyms) # Test with 'contador' print(get_spanish_synonyms('contador'))
Sample Output:
You'll get a list like this (depending on the synsets):['contable', 'contador', 'contador público', 'medidor', 'registrador', 'tesorero']
Method 2: Use spaCy + spacy-wordnet
spaCy's Spanish models paired with the spacy-wordnet extension offer a more robust way to get context-aware synonyms (great if you need to account for different meanings of "contador"—like accountant vs. counter/measurer):
Install the required packages:
pip install spacy spacy-wordnet python -m spacy download es_core_news_smWrite the script to extract synonyms:
import spacy from spacy_wordnet.wordnet_annotator import WordnetAnnotator # Load the Spanish spaCy model nlp = spacy.load('es_core_news_sm') # Add the WordNet annotator to the pipeline nlp.add_pipe("spacy_wordnet", after='tagger') def get_spacy_synonyms(word): doc = nlp(word) synonyms = set() # Iterate over each token's WordNet synsets for token in doc: # Get all Spanish synonyms from WordNet for synset in token._.wordnet.synsets(): for lemma in synset.lemmas(lang='es'): synonyms.add(lemma.name().replace('_', ' ')) # Remove the original word and sort synonyms.discard(word) return sorted(synonyms) # Test with 'contador' print(get_spacy_synonyms('contador'))
Sample Output:
This might return a slightly more comprehensive list, including context-specific terms:['contable', 'contador público', 'medidor', 'registrador', 'tesorero', 'contador de historias']
Both methods work well—use Method 1 for a quick, lightweight solution, or Method 2 if you need better handling of word senses and context.
内容的提问来源于stack exchange,提问作者Manuel Antonio Sanchez

