'Is there a way to return only the first word in a set
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'}
Solution 1:[1]
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")))
Solution 2:[2]
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.
Solution 3:[3]
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:.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hc_dev |
| Solution 2 | mozway |
| Solution 3 |
