line = self.classifIEr.stderr.readline()
请注意,我不能使用通信:因为需要多次调用func2(分类器,向量),它会抛出异常.
import subprocessimport pathsimport os.pathclass CRFClassifIEr: def __init__(self,name,model_type,model_path,model_file,verbose): self.verbose = verbose self.name = name self.type = model_type self.model_fname = model_file self.model_path = model_path if not os.path.exists(os.path.join(self.model_path,self.model_fname)): print 'The model path %s for CRF classifIEr %s does not exist.' % (os.path.join(self.model_path,self.model_fname),name) raise OSError('Could not create classifIEr subprocess') self.classifIEr_cmd = '%s/crfsuite-stdin tag -pi -m %s -' % (paths.CRFSUITE_PATH,os.path.join(self.model_path,self.model_fname))# print self.classifIEr_cmd self.classifIEr = subprocess.Popen(self.classifIEr_cmd,shell = True,stdin = subprocess.PIPE,stderr = subprocess.PIPE) if self.classifIEr.poll(): raise OSError('Could not create classifIEr subprocess,with error info:\n%s' % self.classifIEr.stderr.readline()) #self.cnt = 0 def classify(self,vectors):# print '\n'.join(vectors) + "\n\n" self.classifIEr.stdin.write('\n'.join(vectors) + "\n\n") lines = [] line = self.classifIEr.stderr.readline() while (line.strip() != ''):# print line lines.append(line) line = self.classifIEr.stderr.readline() if self.classifIEr.poll(): raise OSError('crf_classifIEr subprocess dIEd') predictions = [] for line in lines[1 : ]: line = line.strip()# print line if line != '': fIElds = line.split(':')# print fIElds label = fIElds[0] prob = float(fIElds[1]) predictions.append((label,prob)) seq_prob = float(lines[0].split('\t')[1]) return seq_prob,predictions def poll(self): """ Checks that the classifIEr processes are still alive """ if self.classifIEr is None: return True else: return self.classifIEr.poll() != None
为输入文件创建分类器对象,该输入文件是具有句子列表的文档,并且在创建时它还使用该句子列表执行外部命令.然后在单独的函数中处理每个句子,为每个句子提供单独的向量.这个新向量被传递给classify函数.
def func2(): classifIEr=create a classifIEr object for an input file,this executes the external command for sentence in sentences: vectors=process(sentence)# some external function classifIEr.classify(features)解决方法 在classify方法而不是构造函数中初始化self.classifIEr,并使用Popen().还需要使用stdout而不是stderr. 总结
以上是内存溢出为你收集整理的popen与python在python2.7中读取和写入块全部内容,希望文章能够帮你解决popen与python在python2.7中读取和写入块所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)