0

I'm trying to execute some Python code in C# using Pythonnet. In particular, I'm trying to run some basic NLP operations using the NLTK library, such as get the hyponyms of a given WordNet synset. No matter what I do, the returned generator object in my C# code is always empty.

The code below represents the Python and C# counterparts of what I'm trying to do. Whereas in Python it works flawlessly by returning the hyponyms of a given synset, in C# it does not work, since it does not enter into the foreach loop. Plus, I checked if the generator object is empty with .next() and it simply returns it is empty, but not in Python. It looks as if the C# lambda expression was not doing its job.

hyponyms = lambda x:x.hyponyms()
synset_example = wn.synset("body_of_water.n.01")
clos = synset_example.closure(hyponyms)       
list = []
        for hyponym in clos:
            for word in hyponym.lemma_names("eng"):
               list.append(word)
List<string> list = new List<string>();
using (Py.GIL())
{
dynamic nltk = Py.Import("nltk.corpus");
dynamic wn = nltk.wordnet;        
Func<dynamic, dynamic> hyponyms = x => x.hyponyms();
dynamic synsetExample = wn.synset("body_of_water.n.01");
dynamic clos = synsetExample.closure(hyponyms);
foreach (dynamic hyponym in clos)
{  
  foreach (dynamic word in hyponym.lemma_names("eng"))
  {
    string hyp = word.ToString();
    list.Add(hyp);
  }

}

In Python, it enters into the for loop and .next() function shows the generator object is not empty. In the case of C#, it does not, and checking whether it is empty or not with .next(), it returns "".

1 Answers1

1

You are likely right that the problem is with the lambda expression not executing properly. Try making it a python lambda instead:

dynamic hyponyms = PythonEngine.Eval("lambda x: x.hyponyms()");

I didn't delve deep enough to understand why the C# lambda doesn't work. My guess is that pythonnet passes the compiled lambda to python to execute in some way and that way will not know what to do with x.hyponyms().

cudima
  • 414
  • 4
  • 11