Aarushi Aiyyar
Aarushi Aiyyar

Reputation: 369

Printing synsets of words in a list in python

I wish to print synonyms of all the words of the list list

    from nltk.corpus import wordnet
    syns = []
    x = 0
    lst = ['performance','camera', 'ram', 'cost', 'battery']
    for r in lst:
        syns = wordnet.synsets(r)
        i = len(syns)
        for x in range(0, i):
            print(syns[x].lemmas()[x].name())

But I get the following error:

  Traceback (most recent call last):
     File "ontology.py", line 9, in <module>
      print(syns[x].lemmas()[x].name()) 
IndexError: list index out of range

Upvotes: 1

Views: 1107

Answers (1)

cs95
cs95

Reputation: 402333

I'd recommend using a dictionary indexed by words to hold your synonyms. You will need 3 loops:

  1. The outermost loop iterates over each word
  2. The mid loop iterates over each synset for a word
  3. The innermost loop iterates over each lemma per synset

You can append each lemma to its corresponding synset list.

words = ['performance','camera', 'ram', 'cost', 'battery']
syns = {w : [] for w in words}

for k, v in syns.items():
    for synset in wordnet.synsets(k):
        for lemma in synset.lemmas():
            v.append(lemma.name())

print(syns)

{'battery': ['battery',
  'battery',
  'electric_battery',
  'battery',
  'battery',
  'battery',
  'stamp_battery',
  'barrage',
  'barrage_fire',
  'battery',
  'bombardment',
  'shelling',
  'battery',
  'assault_and_battery'],
 'camera': ['camera',
  'photographic_camera',
  'television_camera',
  'tv_camera',
  'camera'],
 'cost': ['cost',
  'monetary_value',
  'price',
  'cost',
  'price',
  'cost',
  'toll',
  'cost',
  'be',
  'cost'],
 'performance': ['performance',
  'public_presentation',
  'performance',
  'performance',
  'execution',
  'carrying_out',
  'carrying_into_action',
  'performance',
  'operation',
  'functioning',
  'performance'],
 'ram': ['random-access_memory',
  'random_access_memory',
  'random_memory',
  'RAM',
  'read/write_memory',
  'Aries',
  'Ram',
  'Aries',
  'Aries_the_Ram',
  'Ram',
  'ram',
  'ram',
  'tup',
  'ram',
  'ram_down',
  'pound',
  'force',
  'drive',
  'ram',
  'crash',
  'ram',
  'jam',
  'jampack',
  'ram',
  'chock_up',
  'cram',
  'wad']}

Upvotes: 2

Related Questions