当前位置: 首页>>代码示例>>Python>>正文


Python PyDictionary.synonym方法代码示例

本文整理汇总了Python中PyDictionary.PyDictionary.synonym方法的典型用法代码示例。如果您正苦于以下问题:Python PyDictionary.synonym方法的具体用法?Python PyDictionary.synonym怎么用?Python PyDictionary.synonym使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyDictionary.PyDictionary的用法示例。


在下文中一共展示了PyDictionary.synonym方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: game

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
def game():
    words = create_word_list()
    lookup = PyDictionary()
    global attempts, wins
    idx = 0
    answer = random.choice(words)
    while idx < 3:
        clue = lookup.synonym(answer)[idx]
        now = time.time()
        future = now + 10
        print('\nClue: ' + clue)
        guess = input('Guess: ').lower()
        if guess == answer or guess + 's' == answer or guess == answer[:-3]:
            print("\nCorrect!")
            wins += 1
            break
        elif now > future:
            print("You ran out of time! The answer was %s." % answer)
            break
        else:
            print("\nWrong.")
            idx += 1
            if idx == 3:
                print("\nThe answer was %s." % answer)

    attempts += 1
    print("Game over. Your score was %d / %d." % (wins, attempts))
    print('-' * 10)
    words.remove(answer)
    restart()
开发者ID:reeses-pieces,项目名称:word_games,代码行数:32,代码来源:password.py

示例2: dictionary

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
def dictionary(command):
    dictionary = PyDictionary()
    words = command.split()

    choice = words[0]
    word = str(words[-1])

    print(choice)
    print(word)
    try:
        if choice == "define":
            definition = str(dictionary.meaning(word))
            return(definition)
        elif choice == "synonyms":
            synonyms = dictionary.synonym(word)
            result = ', '.join(synonyms)
            print(result)
            return result
        elif choice == "antonyms":
            antonyms = dictionary.antonym(word)
            result = ', '.join(antonyms)
            print(result)
            return result
        else:
            return "Please retry your question"
    except TypeError:
        return ("Your word had no " + choice)
开发者ID:jcallin,项目名称:eSeMeS,代码行数:29,代码来源:dictionary.py

示例3: DictExpandQuery

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
def DictExpandQuery(q_terms, k=5):
    dic = PyDictionary()
    
    new_terms = []

    for term in q_terms:
        if isStopWord(term):
            continue

        # check if word exists in the dictionary
        w_found = True
        try:
            dic.meaning(term)
        except:
            w_found = False        
            
        # get k first synonyms
        if w_found:
            try:
                synonyms = dic.synonym(term)
            except:
                continue 

            if synonyms == None:
                continue

            if len(synonyms) > k:
                synonyms = synonyms[:k]
            new_terms.extend(synonyms)

    new_query_terms = q_terms + new_terms

    return new_query_terms
开发者ID:HemanthShetty,项目名称:CS6200Project,代码行数:35,代码来源:QueryExpansion.py

示例4: synonym

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
    async def synonym(self, word):
        """Checks the dictionary for the synonyms for a given word."""

        word = word.lower()
        result = dictionary.synonym(word)
        try:
            text = self.nym_text_format("synonyms", result, word)
            return await self.bot.say(text)
        except TypeError:
            return await self.bot.say("No results found. Are you " +
                                      "searching for a valid word?")
开发者ID:PookaMustard,项目名称:ushiromiya-beatrice,代码行数:13,代码来源:dictionary.py

示例5: Synsets

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
class Synsets(object):
    def __init__(self, synsets={}): # synsets are hashmap of (string:Word objects) pair
        self.dictionary = PyDictionary()
        self.synsets = synsets

    def find(self, word):
        try:
            return map(str, self.dictionary.synonym(word))
        except:
            if word not in synsets:
                return []
            return synsets[word].synonyms

    def add(self, synsets):
        self.synsets.update(synsets)
开发者ID:bsoe003,项目名称:notefy_rest_api,代码行数:17,代码来源:synonyms.py

示例6: Meaning

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
class Meaning():
	def __init__(self):
		self.dictionary=PyDictionary()
	def meaning_function(self,query,task="mn"): #task can be meaning, translate,
		fo=open("meaning.txt","w")
		if task == "mn" :
			fo.write("Meaning :")
			fo.write(str(self.dictionary.meaning(query)))
			fo.write("Synonym :")
			fo.write(str(self.dictionary.synonym(query)))
			fo.write("Antonym :")
			fo.write(str(self.dictionary.antonym(query)))
			print (self.dictionary.meaning(query))
		elif task =="tr":
			fo.write("Translation :")
			unicodedata.normalize('NFKD', self.dictionary.translate(query,'hi')).encode('ascii','ignore')
			fo.write(unicodedata.normalize('NFKD', self.dictionary.translate(query,'hi')).encode('ascii','ignore')) ##Unicode to string conversion
			print(self.dictionary.translate(query,'hi'))
		fo.close()
	def __del__(self):
		os.remove("meaning.txt")
开发者ID:SDES-IITB-course-archive,项目名称:SDES_Readout,代码行数:23,代码来源:Meaning.py

示例7: print

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]

# However, this becomes tedious if we want to keep adding additional keywords such as 'aircraft'.  
# A better approach is to, for example, include synonyms for the word 'airplane'.  
# 
# We can do this using one of the above libraries but we could also use `PyDictionary`, `pip install PyDictionary`

# In[39]:

from PyDictionary import PyDictionary
dictionary=PyDictionary()


# In[40]:

print(dictionary.synonym('airplane'))


# In[41]:

plane_words = dictionary.synonym('airplane') + ['airplane', 'flight']


# In[42]:

for x in submission_titles:
    if 'egypt' in x.lower():
        if any(word in x.lower() for word in plane_words):
            print(x)

开发者ID:mitzipp,项目名称:opensource_workshop,代码行数:30,代码来源:4_text_mining.py

示例8: PyDictionary

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
    words2d = [{i[0] : i[-1]} for i in reader]

pd = PyDictionary()
enhanced_word_sets = []  # Дополненные списки слов(включая синонимы) - обычно в 5 раз длиннее
MATRIX = [[0]*2346]*2346

for words in words2d[1:]:
    res = set()
    id = [int(i) for i in words.keys()][0]
    if words:
        for value in words.values():  # Обходим каждое слово, превращаем его в синонимы, добавляем в сет
            en_words = [word for word in TextBlob(value).translate("ru").split() if word not in
"a about an are as at be by com for from how in is it of on or that the this to was what when where who will with the"]
            rus_synonyms = ""
            for word in en_words:
                synonyms = pd.synonym(word.split()[-1])
                if synonyms:
                    rus_synonyms += " ".join(synonyms) + " "
        for word in TextBlob(rus_synonyms).translate("en", "ru").split():
            res.add(word)

    print("Завершено создание расширенного списка слов для", id, "из 2346")
    enhanced_word_sets.append((id, res))

i = 1
for set_ in enhanced_word_sets:
    for _set in enhanced_word_sets:
        _id_ = set_[0], _set[0]
        if not _id_[0] == _id_[1]:
            index = len(set_[1] & _set[1]) / len(set_[1] | _set[1])  # Индекс схожести
            if 0.25 <= index < 1:
开发者ID:thepowerfuldeez,项目名称:Tasks,代码行数:33,代码来源:analytics_old.py

示例9: getSyn

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
def getSyn(word):
    dic = PyDictionary() 
    syn = dic.synonym(word)
    return syn
开发者ID:santoshvamsee,项目名称:Answering-Remedia-Courpus-using-Natural-Language-Processing,代码行数:6,代码来源:solve_remedia.py

示例10:

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
        print bot_response
    elif message.strip().split()[0] == "tweet":
        flag = None
        tw = Tweets_cassandra.TweetAPI()
        try:
            flag = 0
            tw.postTweet(" ".join(message.strip().split()[1:]))
        except:
            flag = 1
        if (flag == 0 ):
            print "Tweet successful"
        else:
            print "Tweet Failed"

    elif " ".join(message.strip().lower().split()[:2]) == "synonym of":
        bot_response =  dictionary.synonym(" ".join(message.strip().lower().split()[2:]))
        if(len(bot_response) >= 1 ):
            bot_response = ", ".join(bot_response)
        else:
            bot_response = "Sorry i couldn't find the synonym for "," ".join(bot_response)
        print bot_response

    elif " ".join(message.strip().lower().split()[:2]) == "antonym of":        
        bot_response =  (dictionary.antonym(" ".join(message.strip().lower().split()[2:])))
        if(len(bot_response) >= 1 ):
            bot_response = ", ".join(bot_response)
        else:
            bot_response = "Sorry i couldn't find the antonym for "," ".join(bot_response)
        print bot_response

开发者ID:pipa0979,项目名称:HackCU2016,代码行数:31,代码来源:bot.py

示例11: len

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
import nltk
from nltk import pos_tag
from nltk.corpus import wordnet as wn
from PyDictionary import PyDictionary
#from iertools import chain
dictionary=PyDictionary()
text = nltk.word_tokenize("instantiate variable")
tags= nltk.pos_tag(text)
words=[]
for word in tags:
	if word[1] == 'NN' and len(word[0])>1:
		words.append(word[0])
		print dictionary.synonym(word[0])
		print word

'''
synonyms = wordnet.synsets(text)
lemmas = set(chain.from_iterable([word.lemma_names() for word in synonyms]))
wn.synsets('make', pos='v')'''
开发者ID:prodo56,项目名称:compiler,代码行数:21,代码来源:tagging.py

示例12: str

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
# Access most recent Tweet from account
tweets = api.user_timeline('RelatedWordsBot')
mostRecent = tweets[0]

contents = str(mostRecent.text)
index = 0

for x in range(0, len(contents)):
    if (contents[x] == " "):
        index = x

# Word to generate related word from
searchWords = contents.split(" ")
searchWord = searchWords[len(searchWords) - 2].replace(" ", "")

relatedWords = dictionary.synonym(searchWord)

relatedWord = relatedWords[0]

# Word previously generated by bot
prevWord = contents[0 : index]

# Get the image previously generated by the bot
for media in mostRecent.entities.get("media",[{}]):
    #checks if there is any media-entity
    if media.get("type",None) == "photo":
        # checks if the entity is of the type "photo"
        imgUrl = media["media_url"]
        # save to file etc.

result = sbi.search_by(url=imgUrl)
开发者ID:nbond211,项目名称:RelatedWordsBot,代码行数:33,代码来源:RelatedWordsBot_search&combine.py

示例13: zip

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
     input = response
     (a,b,c,d) =[t(s) for t,s in zip((str,int,str,int),re.search('^(\w+) (\d+) (\w+) (\d+)$',input).groups())]
     result = int(b*d)
     print(result)
 elif('divide') in response :
     input = response
     (a,b,c,d) =[t(s) for t,s in zip((str,int,str,int),re.search('^(\w+) (\d+) (\w+) (\d+)$',input).groups())]
     result = float(b/d)
     print(result)
 elif('define') in response:
     query = response
     stopwords = ['define']
     querywords = query.split()
     resultwords  = [word for word in querywords if word.lower() not in stopwords]
     result = ''.join(resultwords)
     rand = (dictionary.synonym(result))
     print(rand)
 elif('tell me a joke')in response:
     rand=(pyjokes.get_joke())
     print(rand)
 elif response == ("do you have a brother"):
     print("yes")
 elif response == "thanks" or response == "thank you":
     print("mhm")
 elif response == ("what is your brothers name"):
     print("jarvis")
 elif response == ("who created you"):
     print("zpit367")
 elif response == ("what language were you coded in"):
     print("python")
 elif response == "what is your name":
开发者ID:ultimatepritam,项目名称:Jarvis,代码行数:33,代码来源:Jarvia.py

示例14: range

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
import twitter
#put all your special keys here
api = twitter.Api(consumer_key='',
                      consumer_secret='',
                      access_token_key='',
                      access_token_secret='')


printout = ""
#list of games
gamelist = ['Call of* Duty :* Advanced Warfare', 'The* Elder Scrolls IV:* Oblivion', 'Half Life 2', 'Faster Than* Light', 'Empire :* Total War', 'Call of* Cthulhu:* Dark Corners of* the* Earth', 'Kerbal* Space Program', 'Splinter Cell :* Chaos Theory', 'The* Curse of* Monkey Island', 'Operation Flashpoint :* Cold War Crisis', 'Company of* Heroes 2*', 'Mass Effect 2*', 'Thief II:* The* Metal Age', 'The* Last of* Us', 'Metal Gear Solid 4:* Guns of* the* Patriots', 'Street Fighter II*', 'Dragon Age :* Inquisition', 'The* Legend of* Zelda:* Ocarina* of* Time', 'Red Dead Redemption', 'Time Splitters :* Future Perfect', 'Uncharted 2:* Among Theives', 'Grand Theft Auto :* Vice City', 'Unreal Tournament', 'Middle earth :* Shadow of Mordor*', 'God of* War', 'Rollercoaster Tycoon', 'Mine Craft', 'World of* War Craft', 'League of* Legends', 'Mount and* Blade :* War band', 'System Shock 2*', 'Team Fortress 2*', 'Alien :* Isolation', 'Hit Man :* Blood Money', 'Star Wars :* Knights Of* The* Old Republic', 'Tony* Hawk \'s* Pro Skater 2*', 'Tony* Hawk \'s* Pro Skater 3*', 'Perfect Dark', 'Metroid* Prime', 'Halo:* Combat Evolved', 'Out of* the* Park Baseball 2007*', 'Resident Evil 4*', 'Mass Effect 2*', 'Baldur\'s* Gate II:* Shadows of Amn*', 'Little Big Planet', 'World of Goo', 'Bio Shock Infinite', 'Final Fantasy IX*', 'Devil May Cry', 'Civilization IV*', 'Quake', 'Ninja Gaiden* Black', 'Jet Grind Radio', 'Burnout 3:* Takedown']
#splits a random game from the list and puts the words in another list
splitlist = gamelist[randint(0, (len(gamelist)-1))].split()
for i in range(0, (len(splitlist))):
#here you take each word, get a list of synonyms, choose a random one
	synonym = dictionary.synonym(splitlist[i])
#if the word has a * at the end, it is preserved	
	if splitlist[i][-1] == '*':
	    printout = printout + " " + splitlist[i][:len(splitlist[i])-1]
#if there are no synonyms, the word is preserved
	elif len(synonym) is True:
		printout = printout + " " + splitlist[i]
#random synonym is chosen	
	else:
		printout = printout + " " + synonym[randint(0, (len(synonym)-1))]
#reformats the colons
printout = printout.replace(' :', ':')
#capitalises the words
status = api.PostUpdate(printout.title())
print status.text
开发者ID:chromebookbob,项目名称:Python-Twitter-Bot,代码行数:32,代码来源:synonymbot-Github.py

示例15: dict

# 需要导入模块: from PyDictionary import PyDictionary [as 别名]
# 或者: from PyDictionary.PyDictionary import synonym [as 别名]
# STEP 5: BODYPARTS ##########################################################################

# We want to first get every synonym for every body part, then search in text.
terms = json.load(open("data/simpleFMA.json","r"))
dictionary=PyDictionary()

# looked at these manually, these are the ones worth adding
get_synsfor = ["stomach","cartilage","breast","knee","waist","muscle","tendon","calf",
               "vagina","penis","back","butt","forearm","thigh"]

bodyparts = dict()
for term,fma in terms.iteritems():
    syns = ""
    word = term.replace("_"," ")
    if term == "index-finger":
        syns = dictionary.synonym("index-finger")
    elif term in get_synsfor:
        syns = dictionary.synonym(term)
    if syns != "":
        regexp = "|".join([word] + syns)
    else:
        regexp = "|".join([word])
    bodyparts[term] = regexp
    
save_json(bodyparts,"data/bodyparts.json")

# Now let's parse each death for bodyparts
injuries = pandas.DataFrame(columns=bodyparts.keys())

for row in fatalities.iterrows():
    index = row[0]
开发者ID:vsoch,项目名称:bodymap,代码行数:33,代码来源:prepare_bodymap.py


注:本文中的PyDictionary.PyDictionary.synonym方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。