我使用NetWorkx模块查找图中两点之间的所有最短字符串。
每个细节都运行良好;一旦两个点之间没有路径,我的脚本就会停止,并且不适用于其他对(起点、到达点)。
因此,我想知道如何添加一个条件,以便当两点之间没有路径时,我会打印以下消息"No way between two points“,然后继续处理其他结对
下面是我的代码:
import networkx as nx
from collections import defaultdict
dd=defaultdict(set)
P=[]
#File content all couples (starting point, end point) to test
with open("3080_interactions_pour_736.txt","r") as f0:
for lignes0 in f0:
lignes0=lignes0.rstrip('\n').split(" ")
prot1=lignes0[0]
prot2=lignes0[1]
couple=prot1,prot2
P.append(list(couple))
#print(P)
#File containing all the binary interactions composing my graph
with open("736(int_connues_avec_scores_sup_0).txt","r") as f1:
for lignes in f1:
if lignes.startswith('9606'):
lignes=lignes.rstrip('\n').split(" ")
proteine1=lignes[2]
proteine2=lignes[3]
dd[proteine1].add(proteine2)
#For every couple of my first file, I apply the module of the shortest chains:
for couples in P:
prot1=couples[0]
prot2=couples[1]
Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])
print("")
print("The first protein in the chain is", prot1)
print("The last protein in the chain is", prot2)
print("")
print("Minimal size chain(s):")
print("")
for chaines in Lchaines:
#To have chains of size 11 maximum
if len(chaines) <= 11:
print(' '.join(chaines))
else :
print('ERROR - The minimum size of the chains exceeds the limit')
break
print("")
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")下面是我收到的错误消息:
Traceback (most recent call last):
File "C:\Users\loisv\Desktop\pluscourtchemin.py", line 26, in <module>
Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])
File "C:\Users\loisv\Desktop\pluscourtchemin.py", line 26, in <listcomp>
Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])
File "C:\Users\loisv\AppData\Local\Programs\Python\Python37-32\lib\site-packages\networkx\algorithms\shortest_paths\generic.py", line 481, in all_shortest_paths
'from Source {}'.format(target, source))
networkx.exception.NetworkXNoPath: Target IKBKE cannot be reachedfrom Source LCK感谢您的帮助:)
发布于 2019-07-12 06:10:22
我不能测试它,但是如果你得到了异常,那么你应该使用try/except
并且您应该为Lchaines赋值(即,空列表),因为异常可能不会创建此变量,并且您将在其他位置出现错误。
try:
Lchaines = [p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)]
except networkx.exception.NetworkXNoPath:
print("No way between these two points")
Lchaines = []或者,您可以使用continue跳过此循环中的其余代码
try:
Lchaines = [p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)]
except networkx.exception.NetworkXNoPath:
print("No way between these two points")
continuehttps://stackoverflow.com/questions/56997828
复制相似问题