#!/usr/bin/env python3

import requests
import sys

from conceptnet5.nodes import normalized_concept_name, uri_to_lemmas
from conceptnet5.query import lookup
# https://github.com/commonsense/conceptnet5/blob/master/conceptnet5/nodes.py
# https://github.com/commonsense/conceptnet5/wiki/API

# How to test in a terminal : 
#   python3
#   from conceptnet2 import *
#   associatedWords('elected','/r/RelatedTo')
#   normalize('elected')

# Run `./conceptnet.py banana` to search words related to banana.

default_language = 'en'

def normalize(language,word):
    return normalized_concept_name(language, word)

def associatedWords(uri,relations):
    """
        Return words related to the given word by the given relations.
    """
    r = list(lookup(uri,limit=100))
    node = [w['start'] for w in r 
                       if w['end'] == uri
                          and w['rel'] in relations 
                          and w['start'].startswith('/c/'+default_language)]
    node = [' '.join(uri_to_lemmas(w)) for w in node if '_' not in w]
    return set(node)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("Syntax: ./%s <word to search>" % sys.argv[0])
    word=normalize(default_language,sys.argv[1])
    uri = "/c/{0}/{1}".format(default_language,word)
    print(associatedWords(uri,{'/r/RelatedTo'}))
    #print(associatedWords(uri,{'/r/CapableOf'},{'/r/RelatedTo', '/r/Synonym', '/r/Causes', '/r/DerivedFrom'}))

@@ -43,16 +43,99 @@
 port sys
+%0Aimport difflib # string similarity%0Aimport functools # partial function application
 %0A%0Afrom c
@@ -686,16 +686,185 @@
  word)%0A%0A
+def similarity(word1,word2):%0A    return 1-difflib.SequenceMatcher(a=word1.lower(), b=word2.lower()).ratio() # the lower is the result the most similars are the 2 words%0A%0A
 def asso
@@ -879,16 +879,21 @@
 rds(uri,
+word,
 relation
@@ -1226,16 +1226,234 @@
 guage)%5D%0A
+    '''for w in r:%0A        if w%5B'end'%5D == uri and w%5B'rel'%5D in relations and w%5B'start'%5D.startswith('/c/'+default_language):%0A            print(w%5B'start'%5D + ' ' + w%5B'rel'%5D + ' ' + w%5B'end'%5D + ' ' + str(w%5B'weight'%5D))   '''%0A
     node
@@ -1525,16 +1525,71 @@
  return 
+sorted(node,key = functools.partial(similarity,word)) #
 set(node
@@ -1837,24 +1837,29 @@
 edWords(uri,
+word,
 %7B'/r/Related

add similarity test