今天想用C#调用crfs,可是老出问题。缘由有几点。第一,我对crf不理解,虽然我用cmd跑了一遍,可是根本不理解为何,并且只是草草看了下参数该输入什么,只是了解了形式,没有了解实质。因此在调用的时候,我不知道怎样转移输入输出的参数。另外,crf_learn在cmd运行的时候,用到了一个自带的dll文件我也不知道怎么处理。并且我在网上找相似调用的例子也找不到。第二,对找到的实例代码不熟悉,没有理解每一行代码的含义和做用。第三,不知道怎么输出结果,不会适当的断点。shell
通过一位同窗的帮助,他帮我解决了以问题。最终运行成功。多线程
Console.WriteLine("aaaaa"); //用于测试输出
System.Diagnostics.Process p = new System.Diagnostics.Process(); //开始系统进程
p.StartInfo = new System.Diagnostics.ProcessStartInfo(@"C:\Users\AMY\Desktop\test\crf_learn.exe"); //应用程序路径
p.StartInfo.Arguments = @" C:\Users\AMY\Desktop\test\template C:\Users\AMY\Desktop\test\train.data C:\Users\AMY\Desktop\test\model"; //参数输入
p.StartInfo.RedirectStandardOutput = true; //结果输出
p.StartInfo.UseShellExecute = false; //是否在shell中显示
p.Start();
//p.WaitForExit();
Console.WriteLine("nnnn");测试
p.Close() //要记得释放资源,否则程序会很慢很慢的。
Console.ReadKey();pwa
dll文件在CRFs运行的时候是能够本身找到的,只要你把它和learn.exe文件放在一个文件夹里面。另外test的结果不能经过参数来重定向,因此,只能将输出流保存到字符串,再保存到txt文件。现阶段(2015.11.8)完整的代码为:线程
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;orm
private void start_CRFs_Click_1(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();进程
string TrainDirectory = Train_directoryT.Text;
string ArgumentsStr = tb_Arguments.Text;
string output = "";
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo(TrainDirectory + "crf_learn.exe");
p.StartInfo.Arguments = ArgumentsStr + " " + TrainDirectory + "template " + TrainDirectory + "train.data " + TrainDirectory + "model";
string argStr = p.StartInfo.Arguments;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
tbtrain_result.Text = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();资源
// System.Threading.Thread.Sleep(50000); 最好能用多线程来处理
System.Diagnostics.Process p2 = new System.Diagnostics.Process();
p2.StartInfo = new System.Diagnostics.ProcessStartInfo(TrainDirectory + "crf_test.exe");//须要启动的程序名
p2.StartInfo.Arguments = " -m " + TrainDirectory + "model " + TrainDirectory + "test.data";
p2.StartInfo.RedirectStandardOutput = true;
p2.StartInfo.UseShellExecute = false;
p2.Start();
output = p2.StandardOutput.ReadToEnd();
TbTest_outputT.Text = output;
byte[] buffer = Encoding.Default.GetBytes(output);
File.WriteAllBytes(TrainDirectory + "output.txt", buffer);
p2.Close();
sw.Stop();
TimeSpan ts = sw.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
TimeSpanL.Text = "用时:" + elapsedTime;
}字符串
一些输入输出定义的变量用的时候记得先定义好。cmd
其实不少不会的知识点,或是一些知识点的细节都是百度到的,记得好的笔记真心让人受益不浅。最后程序也算是成功的跑起来了,因此,我把学会的东西记下来,一来是能够往后本身复习,二来也能够跟你们一块儿分享