I modified the following script to my needs (original found at Fully parsable dictionary/thesaurus and written by samplebias [at samplebias, very useful, thank you :)]):
import textwrap
from nltk.corpus import wordnet as wn
POS = {
'v': 'verb', 'a': 'adjective', 's': 'satellite adjective',
'n': 'noun', 'r': 'adverb'}
def info(word, pos=None):
for i, syn in enumerate(wn.synsets(word, pos)):
syns = [n.replace('_', ' ') for n in syn.lemma_names]
ants = [a for m in syn.lemmas for a in m.antonyms()]
ind = ' '*12
defn= textwrap.wrap(syn.definition, 64)
print 'sense %d (%s)' % (i + 1, POS[syn.pos])
n1=str('definition: ' + ('\n' + ind).join(defn))
n2=str(' synonyms:', ', '.join(syns))
if ants:
n3=str(' antonyms:', ', '.join(a.name for a in ants))
if syn.examples:
n4=str(' examples: ' + ('\n' + ind).join(syn.examples))
try:
resp = ("From dictionary:\n%s\n%s\n%s\n%s") %(n1, n2, n3, n4)
except:
try:
resp = ("From dictionary:\n%s\n%s\n%s") %(n1, n2, n3)
except:
try:
resp = ("From dictionary:\n%s\n%s") %(n1, n2)
except:
resp = ("Data not available...")
print
return resp
However, I can tell that I have not modified it very well as it is just wrapped in try/except blocks. But I can’t for the life of me think of a better way to do it (still learning python in an abstract manner). I need it formatted into a variable containing \n as a separator for each line as it is written to a file. Any ideas how I can do this better, and without the lists thing that seems to be happening?
–Define Sunrise
From dictionary:
definition: the first light of day
(‘ synonyms:’, ‘dawn, dawning, morning, aurora, first light, daybreak, break of day, break of the day, dayspring, sunrise, sunup, cockcrow’)
(‘ antonyms:’, ‘sunset’)
examples: we got up before dawn
they talked until morning
thanks! 🙂
Instead of creating a string for each line, just append your text to the output variable from the start.