Home > Software engineering >  Is there a way to return only the first word in a set
Is there a way to return only the first word in a set

Time:05-10

from nltk.corpus import wordnet as wn


def antonyms_for(word):
    antonyms = set()
    for ss in wn.synsets(word):
        for lemma in ss.lemmas():
            any_pos_antonyms = [ antonym.name() for antonym in lemma.antonyms() ]
            for antonym in any_pos_antonyms:
                antonym_synsets = wn.synsets(antonym)
                if wn.ADJ not in [ ss.pos() for ss in antonym_synsets ]:
                    continue
                antonyms.add(antonym)
    return antonyms

print(antonyms_for("bad"))

prints: {'unregretful', 'good'}

is there a way to print only the first word {'unregretful', 'good'} -> {'unregretful'}

CodePudding user response:

If you don't care about the state of the set that's returned, you could use the method pop() on it:

print(antonyms_for("bad").pop())

This will return ONE of the set items. There is no definitive notion of first in a set as they are unordered.

If you expect the first value in alphabetical order then you can use built-in function min():

print(min(antonyms_for("bad")))

CodePudding user response:

You can use iter next:

next(iter(antonyms_for("bad")))

output: 'good' or 'unregretful'

Note that sets are unordered, so there is no way to reliably obtain a given value, it is not random either, you will just get what the hashing algorithm puts first in the python implementation that you are using.

CodePudding user response:

Sets are unordered collections (not sequences), so there is no first or last.

You can transform the iterable set to a sequence, e.g. one of the following data structures

  • list, using constructor list(iterable)
  • tuple, using constructor tuple(iterable)

and then use indexing to obtain the first:

words_set = antonyms_for("bad")
if words_set:
   first_word = tuple(words_set)[0]
   print(f'First antonym: {first_word}')  # expected to print 'unregretful'
else:
   print('No antonym found!')

Since there may be cases with an empty set returned, you may test for the presence of any elements first using if words_set:.

  • Related