我正在尝试在Python中的文件中输出结果但是它既不工作也不显示任何错误。
以下是我的代码:
from collections import namedtuple
from pprint import pprint as pp
final_data = []
inf = float('inf')
Edge = namedtuple('Edge', 'start, end, cost')
class Graph():
def __init__(self, edges):
self.edges = edges2 = [Edge(*edge) for edge in edges]
self.vertices = set(sum(([e.start, e.end] for e in edges2), []))
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
#pp(neighbours)
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
#pp(previous)
s, u = [], dest
while previous[u]:
s.insert(0, u)
u = previous[u]
s.insert(0, u)
return s
start_point = input('Enter the starting point: ')
end_point = input('Enter the ending point: ')
file_name = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
f = open(file_name, 'r')
data = f.readlines()
for line in data:
f_line = line
values = f_line.split()
values[2] = int(values[2])
final_data.append(values)
graph = Graph(final_data)
f = open(output_file, 'a')
result = str(pp(graph.dijkstra(start_point, end_point)))
f.write(result)
注意:忽略缩进
我不确定我到底在哪里弄错了。我尝试使用append(a)和write(w)写入文件,但两者都不起作用。文件的所有路径都是正确的,输入文件读取完好,输出文件也在同一个文件夹中。
答案 0 :(得分:1)
f = open(output_file, 'a')
result = str(pp(graph.dijkstra(start_point, end_point)))
f.write(result)
你要改为:
with open(output_file, 'a') as f:
result = pprint.pformat(graph.dijkstra(start_point, end_point))
f.write(result)
因为pprint.pprint()
是print
的替代,因此具有相同的“原型”,不会返回任何内容。 pprint.pformat
已被制作,因此您可以“打印”到字符串。虽然,你可能想做
with open(output_file, 'a') as f:
pp(graph.dijkstra(start_point, end_point), stream=f)
作为pprint的帮助:
Help on function pprint in module pprint:
pprint(object, stream=None, indent=1, width=80, depth=None)
Pretty-print a Python object to a stream [default is sys.stdout].