使用IronPython通过C#.NET导入Python模块

ToO*_*sIK 5 c# python ironpython nltk

我正在尝试使用IronPython通过C#.NET运行Python类,Python类导入的几个模块是:

import collections
import nltk.classify.util
Run Code Online (Sandbox Code Playgroud)

为了在运行IronPython时导入它们,我使用ScriptEngineGetSearchPath集合来添加Python库位置的路径,如下所示:

ICollection<string> paths = pyEngine.GetSearchPaths();
string dir = @"C:\Python27\Lib\";
paths.Add(dir);
string dir2 = @"C:\Python27\Lib\site-packages\nltk\classify\";
paths.Add(dir2);
pyEngine.SetSearchPaths(paths);
Run Code Online (Sandbox Code Playgroud)

这似乎对集合 Module 运行良好,但不是nltk.classify.util,并且在调用ScriptEngine的Execute方法时出现以下错误:

没有名为nltk.classify.util的模块

即使是util模块也存在于上面指定的路径中.我认为这个问题与在Python类中指定导入的方式有关('.'分隔),只是不确定如何解决它.任何想法出错的地方?

Con*_*ine 8

Python使用包名称的结构来搜索模块,因此如果您要求nltk.classify.util它将nltk\classify\util.py从搜索路径中的每个目录开始查找.

因此,在您的示例中,您希望更改dir2如下:

string dir2 = @"C:\Python27\Lib\site-packages";
Run Code Online (Sandbox Code Playgroud)