def flatten(self, list): return wordnet.flatten(list)
def is_emotion(word, shallow=False, pos=None, boolean=True): """ Guesses whether the word expresses an emotion. Returns True when the word is an emotion. When the boolean parameter is set to False, returns either None or a string hinting at the emotion the word expresses. For example: print is_emotion("blub", pos=wordnet.VERBS, boolean=False) >>> weep Preferably the return value would be an is_basic_emotion(). """ def _return(value): if boolean and value != None: return True elif boolean: return False else: return value if pos == None \ or pos == wordnet.NOUNS: ekman = ["anger", "disgust", "fear", "joy", "sadness", "surprise"] other = ["emotion", "feeling", "expression"] if pos == wordnet.VERBS: ekman = ["anger", "disgust", "fear", "enjoy", "sadden", "surprise"] other = ["empathize", "feel", "express emotion", "express"] if pos == wordnet.ADJECTIVES \ or pos == wordnet.ADVERBS: ekman = ["angry", "disgusted", "fearful", "happy", "sad", "surprised"] other = ["emotional"] word = word.lower().strip() # Check the naive lists first. for i in range(len(commonsense_naive_ekman)): if word in commonsense_naive_ekman[i]: return _return(commonsense_ekman[i]) # Fair competition: # if we shuffle the list we have an equal speed # for each Ekman emotion to scan. from random import shuffle indices = range(len(ekman)) shuffle(indices) # For each Ekman emotion, # take all of its senses, # and check the hyponyms of that sense. for i in indices: emotion = ekman[i] s = wordnet.senses(emotion, pos) for j in range(len(s)): if word in s[j]: return _return(commonsense_ekman[i]) h = wordnet.hyponyms(emotion, j, pos) h = wordnet.flatten(h) if word in h: return _return(commonsense_ekman[i]) # Maybe we get lucky and WordNet has tagged # the word as a feeling. if shallow and wordnet.lexname(word, 0, pos) == "feeling": return _return("feeling") # Take a generalised word like "emotion" # and traverse its hyponyms. # When performing a deep search, # traverse the hyponyms of those hyponyms as well. # Example: "yearning" -> "desire" -> "feeling" for emotion in other: for w in wordnet.flatten(wordnet.hyponyms(emotion, 0, pos)): if word == w: return _return(emotion) if not shallow: if word in wordnet.flatten(wordnet.hyponym(w, 0, pos)): return _return(w) return _return(None)