我想写一些结果我从一个范围的函数得到,但我不明白为什么文件是空的。该功能工作正常,因为我可以在打印机中看到控制台中的结果。首先,我创建了正在工作的文件,因为它已创建;输出文件名取自一个字符串,并且该部分也在工作。所以下面会在指定路径的文件:文件被创建,但不能用Python编写
report_strategy = open(output_path+strategy.partition("strategy(")[2].partition(",")[0]+".txt", "w")
它创建从一个名为“战略”串取名称的文本文件,例如:
strategy = "strategy(abstraction,Ent_parent)"
一个名为“抽象.txt“是在输出路径文件夹中创建的。到现在为止还挺好。但我无法写任何东西到这个文件。我有一个范围的几个整数
maps = (175,178,185)
这是功能:
def strategy_count(map_path,map_id)
下面的循环不会在范围“地图”每个项目的计数返回一个整数:
report_strategy.close()
:
for i in maps:
report_strategy.write(str(i), ",", str(strategy_count(maps_path,str(i))))
和文件在端封闭
现在以下几点:
for i in maps:
print str(i), "," , strategy_count(maps_path,str(i))
确实给我什么,我想在控制台:
175 , 3
178 , 0
185 , 1
我在想什么?该功能起作用,文件被创建。我在控制台中看到输出,但我无法在文件中写入相同的内容。当然,我关闭了文件。
这是读取文本文件(实际上是Prolog文件)的程序的一部分,并运行一个名为Clingo的应答集编程解决方案。然后读取输出以找到发生策略的实例(具有特定规则的一系列操作)。整个代码:
import pmaps
import strategies
import generalization
# select the strategy to count:
strategy = strategies.abstraction_strategy
import subprocess
def strategy_count(path,name):
p=subprocess.Popen([pmaps.clingo_path,"0",""],
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,stdin=subprocess.PIPE)
#
## write input facts and rules to clingo
with open(path+name+".txt","r") as source:
for line in source:
p.stdin.write(line)
source.close()
# some generalization rules added
p.stdin.write(generalization.parent_of)
p.stdin.write(generalization.chain_parent_of)
# add the strategy
p.stdin.write(strategy)
p.stdin.write("#hide.")
p.stdin.write("#show strategy(_,_).")
#p.stdin.write("#show parent_of(_,_,_).")
# close the input to clingo
p.stdin.close()
lines = []
for line in p.stdout.readlines():
lines.append(line)
counter=0
for line in lines:
if line.startswith('Answer'):
answer = lines[counter+1]
break
if line.startswith('UNSATISFIABLE'):
answer = ''
break
counter+=1
strategies = answer.count('strategy')
return strategies
# select which data set (from the "pmaps" file) to count strategies for:
report_strategy = open(pmaps.hw3_output_path+strategy.partition("strategy(")[2].partition(",")[0]+".txt", "w")
for i in pmaps.pmaps_hw3_fall14:
report_strategy.write(str(i), ",", str(strategy_count(pmaps.path_hw3_fall14,str(i))))
report_strategy.close()
# the following is for testing the code. It is working and there is the right output in the console
#for i in pmaps.pmaps_hw3_fall14:
# print str(i), "," , strategy_count(pmaps.path_hw3_fall14,str(i))
您发布的代码看起来很好。请张贴其余的。 – Kevin 2014-09-29 18:50:04
@Kevin我更新了这篇文章,并把这个文件的所有代码。它读取一些其他文件(前三个导入),它们基本上将一些路径名和Prolog规则存储在文本中。 – mdinar 2014-09-29 19:11:57