使用IronPython [c#]执行python脚本

时间:2018-03-25 17:09:58

标签: c# python

我在python中编写了这段代码来绘制dendrogram

import numpy as np
from scipy.cluster.hierarchy import linkage,dendrogram
import matplotlib.pyplot as plt
x = np.array([[2,3],[5,5],[4.3,6],[5.5,4.9],[4.4,5.8],[10,10],[40,40], 
[2.2,5]])
plt.scatter(x[:,0],x[:,1],s=30)
lin=linkage(x,"single")
den=dendrogram(lin,truncate_mode="none")
plt.show()

它正常工作并生成树形图。之后,我想将此代码转换为Python脚本中的方法并在C#项目上执行,以便我可以使用IronPython。

但此部分linkage(x,"single"),truncate_mode =“none”和此行plt.show()的脚本中存在错误,如以下c#代码所示:

  var pySrc =
  @"def Generatedendrogram():
  import numpy as np
  from scipy.cluster.hierarchy import linkage,dendrogram
  import matplotlib.pyplot as plt
  x = np.array([[2,3],[5,5],[4.3,6],[5.5,4.9],[4.4,5.8],[10,10],[40,40]])
  plt.scatter(x[:,0],x[:,1],s=30)

  //There is an error in the next 2 lines
  dendrogram(linkage(x,"single"), truncate_mode = "none")
  plt.show()";

  // host python and execute script
  var engine = IronPython.Hosting.Python.CreateEngine();
  var scope = engine.CreateScope();
  engine.Execute(pySrc, scope);

  // get function and dynamically invoke
  var dendro = scope.GetVariable("Generatedendrogram");
  Generatedendrogram(); 

如何正确编写此脚本?

0 个答案:

没有答案