NLP




Pay Notebook Creator: Salah Ahmed0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

Get synonyms and antonyms

In [20]:
# Crosscompute
word = 'shy'
target_folder = '.'
In [21]:
from os.path import join
try:
    import nltk
except ImportError:
    import sys
    !{sys.executable} -m pip install nltk
    import nltk
nltk.download('wordnet')  
from nltk.corpus import wordnet
[nltk_data] Downloading package wordnet to /home/user/nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
In [22]:
synsets = wordnet.synsets(word)
synsets
Out[22]:
[Synset('shy.n.01'),
 Synset('shy.v.01'),
 Synset('shy.v.02'),
 Synset('diffident.a.02'),
 Synset('shy.s.02'),
 Synset('shy.s.03')]
In [23]:
from itertools import chain
lemmas = list(chain(*[s.lemmas() for s in synsets]))
lemmas
Out[23]:
[Lemma('shy.n.01.shy'),
 Lemma('shy.v.01.shy'),
 Lemma('shy.v.02.shy'),
 Lemma('diffident.a.02.diffident'),
 Lemma('diffident.a.02.shy'),
 Lemma('diffident.a.02.timid'),
 Lemma('diffident.a.02.unsure'),
 Lemma('shy.s.02.shy'),
 Lemma('shy.s.03.shy')]
In [24]:
set([l.name() for l in lemmas])
Out[24]:
{'diffident', 'shy', 'timid', 'unsure'}
In [25]:
[l.name() for lemma in lemmas for l in lemma.antonyms()]
Out[25]:
['confident']
In [26]:
syns = set([lemma.name() for lemma in lemmas])
syns = list(syns - set([word]))
syns
Out[26]:
['timid', 'unsure', 'diffident']
In [27]:
ants = [l.name() for lemma in lemmas for l in lemma.antonyms()]
ants
Out[27]:
['confident']
In [28]:
syns_path = join(target_folder, 'synonyms.txt')
ants_path = join(target_folder, 'antonyms.txt')
with open(syns_path, 'w') as f:
    f.writelines([x + '\n' for x in syns])
print('synonyms_text_path = %s' % syns_path)

if ants:
    with open(ants_path, 'w') as f:
        f.writelines([x + '\n' for x in ants])
    print('antonyms_text_path = %s' % ants_path)
synonyms_text_path = ./synonyms.txt
antonyms_text_path = ./antonyms.txt