通过IronPython在C# .NET中导入Python模块

5

我正在尝试使用IronPython通过C# .NET运行Python类,Python类导入的一些模块包括:

import collections
import nltk.classify.util

为了在运行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);

这似乎对于collections模块运行良好,但对于nltk.classify.util则不行。当调用ScriptEngine的Execute方法时,会出现以下错误:No module named nltk.classify.util
即使util模块存在于上面指定的路径中,我认为问题与Python类中指定导入的方式有关(使用'.'分隔符),但不确定如何解决。您有什么想法在哪里出错了吗?

ToOsIK,你能展示一下如何将模块导入到Python引擎中吗? - Janatbek Orozaly
1个回答

9
Python使用包名结构来查找模块,因此如果您请求 "nltk.classify.util",它将从搜索路径中的每个目录开始查找 "nltk\classify\util.py"。
因此,在您的示例中,您需要按如下更改 "dir2":
string dir2 = @"C:\Python27\Lib\site-packages";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接