作者CYBASTER (复雠の业火)
看板Python
标题[问题]从别的程式呼叫python出现不一样的结果
时间Wed Oct 30 04:35:32 2013
各位版上的python先进大家好:
小弟最近因为研究需求开始接触python,是个完全的新手,
由於小弟的研究领域是文件自动分类,
因此需要用到python里极强大的nltk自然语言处理套件。
但是小弟的程式基础都在C#上,也有已经打造好的文件分类系统,
估计短期内不可能整个用python重新打造出来,
因此最可能的方案还是将文字的处理部份交给python,再接到我以C#打造的系统做分类。
小弟知道这麽做有点逆天行事,但是要把我的作业流程给自动化似乎没有更好的办法,
因此就是利用python的.py档案可以直接执行的特性,让C#呼叫ProcessRun来执行它,
(理论上)效果其实就像从cmd来执行一样,这段在C#里的程式码长这样:
System.Diagnostics.Process ProcessRun = new Process();
ProcessRun.StartInfo.FileName = @"C:\Python27\python.exe";
ProcessRun.StartInfo.Arguments
= Directory.GetCurrentDirectory() + @"\nltkFacade.py";
ProcessRun.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
ProcessRun.StartInfo.UseShellExecute = false;
ProcessRun.StartInfo.RedirectStandardInput = true;
ProcessRun.StartInfo.RedirectStandardOutput = true;
ProcessRun.StartInfo.CreateNoWindow = true;
ProcessRun.Start();
Console.WriteLine("finish execute python script ");
ProcessRun.WaitForExit();
Console.WriteLine(ProcessRun.StandardOutput.ReadToEnd());
ProcessRun.Close();
然後被执行的nltkFacade.py长这个样子:
=========================================================
#-*- coding:big5 -*-
import os #读取程式目前路径用
import sys #为了能够吃进主程式外部输进的参数
import nltk #引入自然语言处理模组
import io #档案io
from nltk.corpus import stopwords #去无用字
import re #需要用正则表示式移除标点与数字
from nltk.corpus import wordnet as wn #2013/10/26改用wordnet来做字根还原
#把下面三个文字处理函式串接在一起
def superTextHandler(inputString):
#先移除无用符号及数字
inputString=removePuncuhationAndNumbers(inputString)
#先转换小写与断词
tokens=lowerAndTokenlization(inputString)
#去无用字
tokensRemoveStopWords= removeStopwords(tokens)
#字根还原
return wordNetStemming(tokensRemoveStopWords)
#这个去无用字函式是从网路上抄来的,确定能用
def removeStopwords(palabras):
print ("remove stopwords activated!")
return [ word for word in palabras if word not in stopwords.words("english") ]
#移除标点与数字,只要排除非英文字母以外的所有字元就好
def removePuncuhationAndNumbers(input):
return re.sub(r"[^A-Za-z\s]+"," ",input)
#重要,符号的取代要用空白键,不然会沾粘
#word net的字根还原函式, 输入已经断词的list
def wordNetStemming(tokens):
str_list = [] #制造一个类似C#里StringBuilder的东西
for token in tokens:
str_list.append(wordNetStemmingOneWord(token)+" ")
#字根还原完了,记得要加那个空白键不然会沾粘
return "".join(str_list) #这就像最终的StringBuilder.ToString
#使用wordnet做单个字词的字根还原,只进行名词与动词,基本上它还是给人呼叫
def wordNetStemmingOneWord(input):
#在python里None应该就是null
try:
if(wn.morphy(input, wn.NOUN)!=None):
input=wn.morphy(input, wn.NOUN)
if(wn.morphy(input, wn.VERB)!=None):
input=wn.morphy(input, wn.VERB)
except Exception, e:
print e
return input
#断词函式,输入尚未断词之字串,同时完成转换小写
def lowerAndTokenlization(input):
try: #不小心读到空字串时会导致断词函式crash,所以用try包起来
return nltk.word_tokenize(input.lower()) #断词
except Exception:
return nltk.word_tokenize("null") #断词
#处理单一的文字档案,读出来改好再写回同一档案
def dealOneFile(para):
orgdoc=io.open(para, "r", encoding="UTF-8")
modifiedDoc=" "
try:
modifiedDoc=orgdoc.read()
except Exception, e:
print e
wholeParagraph=superTextHandler("".join(modifiedDoc))
orgdoc.close()
mdfdoc=io.open(para, "w")
mdfdoc.write(wholeParagraph.decode("UTF-8"))
mdfdoc.close()
print("perform text operation successfully! "+wholeParagraph)
#主程式
if __name__ == '__main__':
#针对我所需要的工作资料夹走访每个档案
for root, dirs, files in os.walk(os.getcwd()+"\\txtFiles\\allStandards\\"):
print ("show folder: "+root) #输出根目录,debug
for f in files:
print ("show file" +os.path.join(root, f)) #输出要改的档案,debug
dealOneFile(os.path.join(root, f)) #执行单一文字档的修改
=======================================================================
而目前小弟遭遇的情况是:
这个nltkFacade.py没有问题,不论从windows上直接点两下执行,
或是从主控台cmd里输入命令列来执行,都可以正确运作,
可是透过C#来呼叫时,它「没有完整执行」,
这个程式是针对一个资料夹里的所有文字档案作修改,
从C#呼叫的结果是「只有其中一部份的档案有顺利被修改」,其他部份则都无动於衷。
然而,由於这个python档案本身在cmd下已经能被正确执行,
在正确执行的状态下当然不会回报任何错误与例外讯息,
但透过C#来呼叫时,C#的Console上并不转达python所负责输出的讯息,
也就是我追踪不到任何Exception的原因,只好来到贵版求援,
恳请各位python高手不吝赐教,帮小弟看看可能的问题在哪,感激不尽!
P.S.小弟还有尝试过用p2exe将这个py档案编译成exe档,
就小弟使用C#的经验,呼叫exe档的结果通常不令人意外,
但是执行exe档的结果仍和执行这个py档案一样,就是只有一部份的文件被修改。
--
灰心丧志的人,如泄了气的皮球,一蹶不振;
消极颓唐的人,如泄了精的鸡巴,无望再举。
而,打个手枪没有目标的痛苦,就是现实世界的残酷。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 130.126.241.12
※ 编辑: CYBASTER 来自: 130.126.241.12 (10/30 04:41)
1F:→ kdjf:把RedirectStandardOutput关掉,console就会有py output了 10/30 08:18
3F:→ timTan:我以前用 Python For .Net 做过一些实验,感觉不错 10/30 11:18
4F:→ timTan:PS : 这不是 Iron Python 10/30 11:19
5F:推 timTan:而你的问题, 也可以查查看 Iron Python 10/30 11:21
6F:→ timTan:还有 C# 应该可以看到 Python 的 Standard Out, 印出来吧 10/30 11:22
谢谢timTan大大的建议,我一开始也在想用Iron Python来接,
但是因为我使用的nltk套件不支援Iron Python只好作罢。 ^^
※ 编辑: CYBASTER 来自: 50.148.113.168 (10/30 12:48)
7F:推 timTan:看可以try 刚刚贴的 还有 python for .NET 10/30 13:56
8F:→ timTan:那根 iron python 是不一样的东西 10/30 13:56
9F:→ kdjf:所以看到exception是什麽了没? 10/30 21:08