commit lab1-stylefixed
This commit is contained in:
parent
67c2869323
commit
6c411c416b
59
oop.py
59
oop.py
|
@ -4,13 +4,10 @@ import re
|
|||
import sys
|
||||
import time
|
||||
from math import isinf, inf
|
||||
|
||||
import matplotlib.patches
|
||||
import networkx as nx
|
||||
import matplotlib.pyplot as plt
|
||||
from typing import Dict, Generator, List, Optional, cast, Tuple
|
||||
from typing import Dict, Generator, List, Optional
|
||||
import random
|
||||
import os
|
||||
|
||||
|
||||
def main():
|
||||
|
@ -23,7 +20,7 @@ def main():
|
|||
i = input("请输入操作(q:退出, 0:读入文件, 1:展示图形, 2:查找桥接词, 3:生成新文本, 4:计算最短路径, 5:随机游走):")
|
||||
if i == "q":
|
||||
sys.exit()
|
||||
if i == "0": #shengchengTu
|
||||
if i == "0":
|
||||
tu = Tu()
|
||||
|
||||
file_name = input("请输入文件名称:")
|
||||
|
@ -59,15 +56,15 @@ def main():
|
|||
print("Invalid input")
|
||||
|
||||
|
||||
|
||||
class Tu:
|
||||
def __init__(self):
|
||||
self.dict = {}
|
||||
self.graph = nx.MultiDiGraph()
|
||||
|
||||
def read_text_file(self,filename):
|
||||
@staticmethod
|
||||
def read_text_file(filename):
|
||||
try:
|
||||
with open(filename, 'r',"UTF-8") as file:
|
||||
with open(filename, 'r', encoding="utf-8") as file:
|
||||
text = file.read()
|
||||
# 用正则表达式将非字母字符替换为空格,并将换行符也替换为空格
|
||||
text = re.sub(r'[^a-zA-Z\n]+', ' ', text)
|
||||
|
@ -80,7 +77,7 @@ class Tu :
|
|||
return []
|
||||
|
||||
def generate_directed_dict(self, word_sequence):
|
||||
graph = self.dict #chunfuzhi,yiqigai
|
||||
graph = self.dict
|
||||
for i in range(len(word_sequence) - 1):
|
||||
current_word = word_sequence[i]
|
||||
next_word = word_sequence[i + 1]
|
||||
|
@ -148,7 +145,8 @@ class Tu :
|
|||
|
||||
return bridge_words
|
||||
|
||||
def print_bridge_words(self,bridge_words,word1,word2):
|
||||
@staticmethod
|
||||
def print_bridge_words(bridge_words, word1, word2):
|
||||
|
||||
if not bridge_words:
|
||||
print("No bridge words from", word1, "to", word2, "!")
|
||||
|
@ -207,6 +205,7 @@ class Tu :
|
|||
return shortest_path_generator, shortest_length
|
||||
except nx.NetworkXNoPath:
|
||||
return None, None
|
||||
|
||||
def find_shortest_path(self, word1, word2):
|
||||
|
||||
try:
|
||||
|
@ -215,6 +214,7 @@ class Tu :
|
|||
return shortest_path_list, shortest_length
|
||||
except nx.NetworkXNoPath:
|
||||
return None, None
|
||||
|
||||
def find_shortest_path_ex(self, word1, word2):
|
||||
|
||||
try:
|
||||
|
@ -227,9 +227,7 @@ class Tu :
|
|||
|
||||
if shortest_path.__len__() == shortest_length:
|
||||
shortest_path_list.append(shortest_path)
|
||||
return(shortest_path_list,shortest_length)
|
||||
|
||||
|
||||
return shortest_path_list, shortest_length
|
||||
except nx.NetworkXNoPath:
|
||||
return None, None
|
||||
|
||||
|
@ -239,7 +237,6 @@ class Tu :
|
|||
|
||||
# !!! HUATU ROLL YANSE
|
||||
|
||||
|
||||
pos = nx.spring_layout(graph)
|
||||
nx.draw_networkx_nodes(graph, pos, node_size=1000, node_color="skyblue")
|
||||
nx.draw_networkx_labels(graph, pos, font_size=10, font_weight="bold")
|
||||
|
@ -257,21 +254,17 @@ class Tu :
|
|||
if (edge in zip(shortest_path[:-1], shortest_path[1:]) or
|
||||
edge in zip(shortest_path[1:], shortest_path[:-1])):
|
||||
|
||||
|
||||
|
||||
|
||||
nx.draw_networkx_edges(graph, pos, edgelist=[edge], width=2.0, edge_color=num,
|
||||
arrows=True,arrowstyle="->",arrowsize=30
|
||||
,connectionstyle='arc3,rad=0.2')
|
||||
arrows=True, arrowstyle="->", arrowsize=30,
|
||||
connectionstyle='arc3,rad=0.2')
|
||||
else:
|
||||
nx.draw_networkx_edges(graph, pos, edgelist=[edge], width=1.0,
|
||||
edge_color="black",
|
||||
arrows=True,arrowstyle="->",arrowsize=30
|
||||
,connectionstyle='arc3,rad=0.2')
|
||||
arrows=True, arrowstyle="->", arrowsize=30,
|
||||
connectionstyle='arc3,rad=0.2')
|
||||
plt.show()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def calcShortestPath(self, word1, word2):
|
||||
if word2 == "":
|
||||
word1 = self.input_check(word1)
|
||||
|
@ -288,7 +281,6 @@ class Tu :
|
|||
self.calc_shortest_path(word1, word2)
|
||||
pass
|
||||
|
||||
|
||||
def calc_shortest_path_old(self, word1, word2):
|
||||
|
||||
shortest_path_generator, shortest_length = self.find_shortest_path_old(word1, word2)
|
||||
|
@ -305,13 +297,10 @@ class Tu :
|
|||
else:
|
||||
print("No path exists between", word1, "and", word2)
|
||||
|
||||
|
||||
def calc_shortest_path(self, word1, word2):
|
||||
|
||||
shortest_path_list, shortest_length = self.find_shortest_path_ex(word1, word2)
|
||||
|
||||
|
||||
|
||||
for shortest_path in shortest_path_list:
|
||||
|
||||
if shortest_path:
|
||||
|
@ -329,7 +318,6 @@ class Tu :
|
|||
filename = input("Enter the filename to save traversal results: ")
|
||||
filename += ".txt"
|
||||
|
||||
|
||||
graph = copy.deepcopy(self.dict)
|
||||
start_node = random.choice(list(graph.keys()))
|
||||
visited_nodes = set()
|
||||
|
@ -344,7 +332,7 @@ class Tu :
|
|||
if input() == "@":
|
||||
file.close()
|
||||
break
|
||||
if graph.get(current_node) != None:
|
||||
if graph.get(current_node) is not None:
|
||||
pass
|
||||
else:
|
||||
break
|
||||
|
@ -364,11 +352,10 @@ class Tu :
|
|||
def randomWalk(self):
|
||||
self.random_traversal()
|
||||
|
||||
|
||||
def input_check(self, input_word):
|
||||
@staticmethod
|
||||
def input_check(input_word):
|
||||
(input_word_re, input_word_ren) = re.subn(r'[^a-zA-Z\n]', ' ', input_word)
|
||||
|
||||
|
||||
if input_word_ren > 0:
|
||||
print("There are illegal signs in your input,the amount is " + str(input_word_ren))
|
||||
|
||||
|
@ -380,7 +367,6 @@ class Tu :
|
|||
|
||||
return tmp[0]
|
||||
|
||||
|
||||
def all_simple_paths_graph(self, source: str, targets: str) -> Generator[List[str], None, None]:
|
||||
G = self.graph
|
||||
cutoff = len(G) - 1 # 设置路径的最大深度,防止无限循环。
|
||||
|
@ -409,14 +395,15 @@ class Tu :
|
|||
stack.pop()
|
||||
visited.popitem()
|
||||
|
||||
def calc_shortest_path_len(self, word1: str, word2: str) -> str | tuple[str, int]:
|
||||
def calc_shortest_path_len(self, word1: str, word2: str) -> int:
|
||||
|
||||
if word1 not in self.graph.nodes or word2 not in self.graph.nodes:
|
||||
return ""
|
||||
return 0
|
||||
|
||||
distances = {node: inf for node in self.graph.nodes}
|
||||
# 存储word1到所有结点的距离,初始化为无穷大
|
||||
previous_nodes: Dict[str, Optional[str]] = {node: None for node in self.graph.nodes} # 存储每个节点最短路径中的前一个节点,初始化为None
|
||||
previous_nodes: Dict[str, Optional[str]] = {node: None for node in
|
||||
self.graph.nodes} # 存储每个节点最短路径中的前一个节点,初始化为None
|
||||
distances[word1] = 0 # 距离初始化为0
|
||||
priority_queue = [(0, word1)] # 优先级队列,用于按照从小到大获取节点
|
||||
|
||||
|
@ -448,7 +435,7 @@ class Tu :
|
|||
path.insert(0, current_node)
|
||||
|
||||
if isinf(distances[word2]): # 目标节点不可达
|
||||
return ("",0)
|
||||
return 0
|
||||
return path.__len__()
|
||||
# return (' '.join(path),path.__len__())
|
||||
|
||||
|
|
Loading…
Reference in New Issue