Table of Content
Big Model Helps You Study - Using LLM to Build Entity Relationship Diagram

Updated on:June-28th-2025
Recommendation
Using big model technology, we explore the relationships between characters in Romance of the Three Kingdoms and open up a new perspective for text analysis.
Core content:
1. Application of big model technology in text entity relationship extraction
2. Practice of domestic big model Wenxin 4.5 and LangChain tool chain
3. Steps for text processing and entity relationship graph construction of Romance of the Three Kingdoms
Yang Fangxian
Founder of 53AI/Most Valuable Expert of Tencent Cloud (TVP)
Jieba: word segmentation tool, Chinese text segmentation, you can also use NLP text processing tools such as hanlp Langchain: A framework for large model development langchain-openai: To simplify the interaction with the large model and obtain the return results of the large model, use the ChatOpenAI interface of langchain-openai to deploy the large model NetworkX: Graph data relationship creation and visualization
# Divide into paragraphs.
def text2paragraphs ( text ):
result = [i.strip() for i in text.split( '\r\n' ) if i]
print ( f"The text can be divided into { len (result)} paragraphs!" )
return result
# Determine whether the token is a sentence terminator and increase it as needed.
def is_sentence_end ( token ):
return token in [ '. ' , '! ' , '? ' , """ ]
# Search backward from the lower boundary of the chunk to the sentence terminator, which is used to dynamically adjust the chunk division to ensure that the chunk ends with a complete sentence
def find_sentence_boundary_forward ( tokens, chunk_size ):
end = len (tokens)
for i in range (chunk_size, len (tokens)): # Search backwards from chunk_size
if is_sentence_end(tokens[i]):
end = i + 1 # includes the end symbol
break
return end
# Start from position start and search forward for the sentence terminator of the previous sentence to ensure that the overlapping parts of the blocks start from a complete sentence.
def find_sentence_boundary_backward ( tokens, start ):
for i in range (start - 1 , - 1 , - 1 ):
if is_sentence_end(tokens[i]):
return i + 1 # includes the end of sentence symbol
return 0 # not found
# Text is divided into blocks. The reference size of a text block is chunk_size, and the reference size of the overlapping part between text blocks is overlap.
# In order to ensure that the overlapping parts between text blocks and the truncated parts at the end of the text block are complete sentences, the size of the text block and the size of the overlapping parts are dynamically adjusted according to the content of the current text block and are floating values.
def chunk_text ( text, chunk_size= 300 , overlap= 50 ):
if chunk_size <= overlap: # parameter check
raise ValueError( "chunk_size must be greater than overlap." )
# First divide it into paragraphs. Paragraphs store semantic information, and process the entire paragraph.
paragraphs = text2paragraphs(text)
chunks = []
buffer = []
# Process each paragraph individually
i = 0
while i < len (paragraphs):
# Fill the buffer until it is larger than chunk_szie, and then read the entire paragraph, which stores semantic information.
while len (buffer) < chunk_size and i < len (paragraphs):
tokens = jieba.lcut(paragraphs[i]) # word segmentation text2token
buffer.extend(tokens)
i += 1
# Current buffer block
while len (buffer) >= chunk_size:
# Dynamically adjust the chunk size to ensure it ends with a complete sentence.
end = find_sentence_boundary_forward(buffer, chunk_size)
chunk = buffer[:end] # includes the rest character
chunks.append(chunk) # Keep the token status for later counting
# Ensure that the overlapping parts start from complete sentences.
start_next = find_sentence_boundary_backward(buffer, end - overlap)
if start_next== 0 :
start_next = find_sentence_boundary_backward(buffer, end- 1 )
if start_next== 0 :
start_next = end - overlap
buffer = buffer[start_next:]
if buffer: # If there are remaining tokens in the buffer
# Check if the remaining part is already included in the last block, it is just left as overlap between blocks.
last_chunk = chunks[ len (chunks)- 1 ]
rest = '' .join(buffer)
temp = '' .join(last_chunk[ len (last_chunk)- len (rest):])
if temp!=rest: # If it is not left for overlap, it is the last block.
chunks.append(buffer)
return chunks
import osfrom langchain.prompts import PromptTemplatefrom langchain.chains import SequentialChain, LLMChainfrom langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage # Configure environment variables. AI_STUDIO_API_KEY can be obtained from your personal accountos.environ["AI_STUDIO_API_KEY"] = "XXX" # Replace with your API_KEYos.environ["MODEL_URL"] = "https://aistudio.baidu.com/llm/lmapi/v3"os.environ["DeepSeek_MODEL"] = "deepseek-r1"os.environ["ERNIE_MODEL"] = "ERNIE-4.5-8K-preview"# Configure large modelllm = ChatOpenAI( base_url=os.environ.get("MODEL_URL"), api_key=os.environ.get("AI_STUDIO_API_KEY"), model=os.environ.get("ERNIE_MODEL"), max_tokens=2048,)
# This prompt refers to Microsoft GraphRAGRAGsystem_template=""" -Goal- Given a relevant text document and a list of entity types, identify all entities of these types from the text and all relationships between the identified entities. -Steps- 1. Identify all entities. For each identified entity, extract the following information: -entity_name: the name of the entity -entity_type: one of the following types: [{entity_types}] -entity_description: a comprehensive description of the entity's attributes and activities Format each entity as ("entity"{tuple_delimiter}<entity_name>{tuple_delimiter}<entity_type>{tuple_delimiter}<entity_description> 2. From the entities identified in step 1, identify all entity pairs (source_entity, target_entity) that are *clearly* related to each other. For each pair of related entities, extract the following information: -source_entity: the name of the source entity, as identified in step 1 -target_entity: the name of the target entity, as identified in step 1 -relationship_type: the relationship type, ensure consistency and generality of the relationship type, use a more general and tenseless relationship type -relationship_description: explain why you think the source entity and target entity are related to each other -relationship_strength: a numeric score indicating the strength of the relationship between the source entity and the target entity Format each relationship as ("relationship"{tuple_delimiter}<source_entity>{tuple_delimiter}<target_entity>{tuple_delimiter}<relationship_type>{tuple_delimiter}<relationship_description>{tuple_delimiter}<relationship_strength>) 3. All attributes of entities and relationships are output in Chinese, and all entities and relationships identified in steps 1 and 2 are output as a list. Use **{record_delimiter}** as the list separator. 4. When completed, output {completion_delimiter}##################### -Example- ################### Example 1:Entity_types: [person, technology, mission, organization, location]Text:while Alex clenched his jaw, the buzz of dull frustration against the backdrop of Taylor's authoritarian certainty. It was this competitive undercurrent that kept him alert, the sense that his and Jordan's shared commitment to discovery was an unspoken rebellion against Cruz's narrowing vision of control and order.Then Taylor did something unexpected. They paused beside Jordan and, for a moment, observed the device with something akin to reverence. "If this tech can be understood..." Taylor said, their voice quieter, "It could change the game for us. For all of us." gravity of what lay in their hands. Jordan looked up, and for a fleeting heartbeat, their eyes locked with Taylor's, a wordless clash of wills softening into an uneasy truce. It was a small transformation, barely perceptible, but one that Alex noted with an inward nod. They had all been brought here by different paths################Output:("entity"{tuple_delimiter}"Alex"{tuple_delimiter}"person"{tuple_delimiter}"Alex is a character who experiences frustration and is observant of the dynamics among other characters."){record_delimiter}("entity"{tuple_delimiter}"Taylor"{tuple_delimiter}"person"{tuple_delimiter}"Taylor is portrayed with authoritarian certainty and shows a moment of reverence towards a device, indicating a change in perspective."){record_delimiter}("entity"{tuple_delimiter}"Jordan"{tuple_delimiter}"person"{tuple_delimiter}"Jordan shares a commitment to discovery and has a significant interaction with Taylor regarding a device."){record_delimiter}("entity"{tuple_delimiter}"Cruz"{tuple_delimiter}"person"{tuple_delimiter}"Cruz is associated with a vision of control and order, influencing the dynamics among other characters."){record_delimiter}("entity"{tuple_delimiter}"The Device"{tuple_delimiter}"technology"{tuple_delimiter}"The Device is central to the story, with potential game-changing implications, and is revered by Taylor."){record_delimiter}("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Taylor"{tuple_delimiter}"workmate"{tuple_delimiter}"Alex is affected by Taylor's authoritarian certainty and observes changes in Taylor's attitude towards the device."{tuple_delimiter}7){record_delimiter}("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Jordan"{tuple_delimiter}"workmate"{tuple_delimiter}"Alex and Jordan share a commitment to discovery, which contrasts with Cruz's vision."{tuple_delimiter}6){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"Jordan"{tuple_delimiter}"workmate"{tuple_delimiter}"Taylor and Jordan interact directly regarding the device, leading to a moment of mutual respect and an uneasy truce."{tuple_delimiter}8){record_delimiter}("relationship"{tuple_delimiter}"Jordan"{tuple_delimiter}"Cruz"{tuple_delimiter}"workmate"{tuple_delimiter}"Jordan's commitment to discovery is in rebellion against Cruz's vision of control and order."{tuple_delimiter}5){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"The Device"{tuple_delimiter}"study"{tuple_delimiter}"Taylor shows reverence towards the device, indicating its importance and potential impact."{tuple_delimiter}9){completion_delimiter}"""which contrasts with Cruz's vision."{tuple_delimiter}6){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"Jordan"{tuple_delimiter}"workmate"{tuple_delimiter}"Taylor and Jordan interact directly regarding the device, leading to a moment of mutual respect and an uneasy truce."{tuple_delimiter}8){record_delimiter}("relationship"{tuple_delimiter}"Jordan"{tuple_delimiter}"Cruz"{tuple_delimiter}"workmate"{tuple_delimiter}"Jordan's commitment to discovery is in rebellion against Cruz's vision of control and order."{tuple_delimiter}5){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"The Device"{tuple_delimiter}"study"{tuple_delimiter}"Taylor shows reverence towards the device, indicating its importance and potential impact."{tuple_delimiter}9){completion_delimiter}"""which contrasts with Cruz's vision."{tuple_delimiter}6){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"Jordan"{tuple_delimiter}"workmate"{tuple_delimiter}"Taylor and Jordan interact directly regarding the device, leading to a moment of mutual respect and an uneasy truce."{tuple_delimiter}8){record_delimiter}("relationship"{tuple_delimiter}"Jordan"{tuple_delimiter}"Cruz"{tuple_delimiter}"workmate"{tuple_delimiter}"Jordan's commitment to discovery is in rebellion against Cruz's vision of control and order."{tuple_delimiter}5){record_delimiter}("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"The Device"{tuple_delimiter}"study"{tuple_delimiter}"Taylor shows reverence towards the device, indicating its importance and potential impact."{tuple_delimiter}9){completion_delimiter}"""
from langchain_core.messages import HumanMessage, SystemMessagefrom langchain.prompts import (ChatPromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate, SystemMessagePromptTemplate)chat_prompt = ChatPromptTemplate.from_messages( [system_message_prompt, MessagesPlaceholder("chat_history"), human_message_prompt])chain = chat_prompt | llmtuple_delimiter = " : "record_delimiter = "\n"completion_delimiter = "\n\n"entity_types = ["Character", "Position", "Weapon", "Battle", "Location"]chat_history = []
import timetuple_delimiter = " : "record_delimiter = "\n"completion_delimiter = "\n\n"entity_types = ["Character", "Position", "Weapon", "Battle", "Location"]chat_history = []chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, MessagesPlaceholder("chat_history"), human_message_prompt])chain = chat_prompt | llm3input_text = ''.join(chunks[0])print("The original text is as follows >>> \n")print(input_text)t0 = time.time()answer = chain.invoke({ "chat_history": chat_history, "entity_types": entity_types, "tuple_delimiter": tuple_delimiter, "record_delimiter": record_delimiter, "completion_delimiter": completion_delimiter, "input_text": input_text})t1= time.time()print("This model takes:",t1-t0,"seconds")print("\n")print(answer.content)print("\n")
Original text as follows>>>However, Sun Jian was surrounded by Liu Biao. Fortunately, Cheng Pu, Huang Gai and Han Dang saved him. Most of his troops were lost, and he took the road to lead his troops back to Jiangdong. Since then, Sun Jian and Liu Biao had a grudge. Yuan Shao stationed his troops in Henei and lacked food and grass. Han Fu, the governor of Jizhou, sent people to send food for military use. The counselor Feng Ji said to Shao: "A real man should roam the world, why should he wait for others to send food for food! Jizhou is a place with abundant money and food, why don't you take it?" Shao said: "I don't have a good plan." Ji said: "You can secretly send someone to send a letter to Gongsun Zan, ordering him to advance troops to take Jizhou, and agree to attack from both sides. Zan will definitely raise troops. Han Fu is a man without strategy, and he will definitely ask the general to take charge of the state; it will be easy to take advantage of it." Shao was very happy and sent a letter to Zan. Zan received the letter and saw that it said that they would attack Jizhou together and divide its land equally. He was very happy and raised troops that day. Shao sent someone to report to Han Fu secretly. Fu hurriedly gathered two counselors, Xun Chen and Xin Ping, to discuss. Chen said: "Gongsun Zan is leading the people of Yan and Dai and marching forward. His front is unstoppable. He also has the help of Liu Bei, Guan Yu and Zhang Fei, so it is difficult to resist him. Now Yuan Benchu is extremely wise and brave, and has many famous generals under his command. You can ask him to help you manage the state affairs. He will definitely treat you well, and you will not have to worry about Gongsun Zan." Han Fu immediately sent Guan Chun to invite Yuan Shao. The chief secretary Geng Wu advised: "Yuan Shao is a lonely guest with a poor army. He depends on me for his survival. It is like a baby in the palm of your hand. If you cut off his milk, he will starve to death. Why do you want to entrust him with the affairs of the state? This is like inviting a tiger into the flock of sheep." Fu said: "I am an old official of the Yuan family, and my ability is not as good as Benchu. In ancient times, people chose the wise and gave them the throne. Why are you jealous?" Geng Wu sighed and said: "Jizhou is over!" So more than 30 people abandoned their posts and left. Only Geng Wu and Guan Chun hid outside the city to wait for Yuan Shao. A few days later, Shao led his troops to arrive. Geng Wu and Guan Chun drew their swords and tried to kill Shao. Shao's general Yan Liang killed Geng Wu and Wen Chou hacked Guan Chun to death. Shao entered Jizhou and appointed Fu as General Fenwei, and Tian Feng, Ju Su, Xu You, and Feng Ji to take charge of the affairs of the state, thus taking away all the power of Han Fu. Fu was so regretful that he abandoned his family and rode alone to join Zhang Miao, the governor of Chenliu. However, Gongsun Zan knew that Yuan Shao had occupied Jizhou, so he sent his brother Gongsun Yue to see Shao and wanted to divide the land. Shao said, "Please ask your brother to come, I have something to discuss." Yue said goodbye and went back. Less than fifty miles away, a group of soldiers and horses flashed by the roadside and said, "I am the general of Prime Minister Dong!" Gongsun Yue was shot dead by arrows. The servants fled back to see Gongsun Zan and reported that Yue was dead. Zan was furious and said, "Yuan Shao lured me to raise an army to attack Han Fu, but he took advantage of the situation; now he tricked Dong Zhuo's soldiers into shooting my brother to death. How can I not avenge this injustice!" He gathered all his troops and rushed to Jizhou. When Shao knew that Zan's troops were coming, he also led his troops out. The two armies met on the Pan River: Shao's army was on the east side of the Pan River Bridge, and Zan's army was on the west side of the bridge. Zan stood on the bridge and shouted, "How dare you sell me out, you traitor!" This model took: 122.43553447723389 seconds**("entity" : "Sun Jian" : "Character" : "Sun Jian was surrounded by Liu Biao, and was rescued by Cheng Pu, Huang Gai, and Han Dang. From then on, he had a grudge against Liu Biao."")("entity" : "Liu Biao" : "Character" : "Liu Biao surrounded Sun Jian, and had a grudge against Sun Jian."")("entity" : "Cheng Pu" : "Character" : "Cheng Pu was a general under Sun Jian, and participated in the rescue of Sun Jian."")("entity" : "Huang Gai" : "Character" : "Huang Gai was a general under Sun Jian, and participated in the rescue of Sun Jian."")("entity" : "Han Dang" : "Character" : "Han Dang was a general under Sun Jian, and participated in the rescue of Sun Jian."")("entity" : "Jiangdong" : "Location" : "After Sun Jian was surrounded by Liu Biao, he took the road and led his troops back to Jiangdong."")("entity" : "Yuan Shao" : "Character" : "Yuan Shao stationed his troops in Henei and was short of food and grass. Later, he listened to Feng Ji's advice and plotted to seize Jizhou."")("entity" : "Henei" : "Location" : "Where Yuan Shao stationed his troops."")("entity" : "Jizhou" : "Location" : "Where Han Fu, the governor of Jizhou, was located. This was where Yuan Shao plotted to seize Jizhou."")("entity" : "Han Fu" : "Character" : "The governor of Jizhou, sent people to send food to support Yuan Shao's army. Later, Yuan Shao used a trick to seize Jizhou."")("entity" : "Feng Ji" : "Character" : "Yuan Shao's adviser, who suggested that Yuan Shao plot to seize Jizhou."")("entity" : "Gongsun Zan" : "Character" : "Yuan Shao secretly sent someone to ask him to march to Jizhou. Later, he learned that Yuan Shao had already occupied Jizhou, so he sent his brother Gongsun Yue to see Shao to divide the land."")("entity" : "Xun Chen" : "Character" : "Han Fu's counselor, suggested Han Fu to ask Yuan Shao to jointly govern the state."")("entity" : "Xin Ping" : "Character" : "Han Fu's counselor, discussed with Xun Chen how to deal with Gongsun Zan."")("entity" : "Liu Bei" : "Character" : "Helped Gongsun Zan to attack Jizhou."")("entity" : "Guan Yu" : "Character" : "Helped Gongsun Zan to attack Jizhou, together with Liu Bei and Zhang Fei."")("entity" : "Zhang Fei" : "Character" : "Helped Gongsun Zan to attack Jizhou, together with Liu Bei and Guan Yu."")("entity" : "Guan Chun" : "Character" : "Han Fu went to invite Yuan Shao, but was hacked to death by Wen Chou."")("entity" : "Geng Wu" : "Character" : "Han Fu's chief secretary, who dissuaded Han Fu from asking Yuan Shao to help govern the state, was immediately beheaded by Yan Liang."")("entity" : "Yan Liang" : "Character" : "Yuan Shao's general, who immediately beheaded Geng Wu."")("entity" : "Wen Chou" : "Character" : "Yuan Shao's general, who hacked Guan Chun to death."")("entity" : "General Fenwei" : "Position" : "The position Han Fu held after Yuan Shao entered Jizhou."")("entity" : "Tian Feng" : "Character" : "After Yuan Shao entered Jizhou, he was in charge of one of the state affairs."")("entity" : "Ju Su" : "Character" : "After Yuan Shao entered Jizhou, he was in charge of one of the state affairs."")("entity" : "Xu You" : "Character" :"After Yuan Shao entered Jizhou, he took charge of one of the affairs of the state."")("entity" : "Chenliu" : "Location" : "Han Fu abandoned his family and went to Chenliu Governor Zhang Miao."")("entity" : "Zhang Miao" : "Person" : "Chenliu Governor, the person Han Fu went to."")("entity" : "Gongsun Yue" : "Person" : "Gongsun Zan's younger brother, shot to death by a general of Prime Minister Dong."")("entity" : "Prime Minister Dong" : "Person" : "Gongsun Yue was shot to death by a general, but his identity was not clearly stated, but it can be inferred that it was a powerful prime minister at the time, such as Dong Zhuo."")("entity" : "Panhe" : "Location" : "The place where Gongsun Zan and Yuan Shao's armies fought."")**("relationship" : "Sun Jian" : "Liu Biao" : "Hostile" : "Sun Jian was surrounded by Liu Biao, and later became enemies with him." : 8)("relationship" : "Sun Jian" : "Cheng Pu" : "Commander" : "Cheng Pu was Sun Jian's general and participated in rescuing Sun Jian." : 9)("relationship" : "Sun Jian" : "Huang Gai" : "Commander" : "Huang Gai was Sun Jian's general and participated in rescuing Sun Jian." : 9)("relationship" : "Sun Jian" : "Han Dang" : "Commander" : "Han Dang was Sun Jian's general and participated in rescuing Sun Jian." : 9)("relationship" : "Sun Jian" : "Jiangdong" : "Retreat to" : "After Sun Jian was surrounded by Liu Biao, he took the road to lead his troops back to Jiangdong." : 7)("relationship" : "Yuan Shao" : "Feng Ji" : "Advisor" : "Feng Ji is Yuan Shao's counselor, and suggests that Yuan Shao plot to seize Jizhou." : 8)("relationship" : "Yuan Shao" : "Jizhou" : "plot" : "Yuan Shao listened to Feng Ji's advice and plotted to seize Jizhou." : 8)("relationship" : "Yuan Shao" : "Han Fu" : "hostile-exploitation" : "Yuan Shao used a strategy to seize Jizhou from Han Fu." : 7)("relationship" : "Han Fu" : "Xun Chen" : "Counselor" : "Xun Chen is Han Fu's counselor, and suggests that Han Fu ask Yuan Shao to help him govern the state." : 7)("relationship" : "Han Fu" : "Xin Ping" : "Counselor" : "Xin Ping is Han Fu's counselor, and together with Xun Chen, he discusses strategies to deal with Gongsun Zan." : 7)("relationship" : "Gongsun Zan" : "Liu Bei" : "Ally" : "Liu Bei helped Gongsun Zan to attack Jizhou." : 6)("relationship" : "Gongsun Zan" : "Guan Yu" : "Ally" : "Guan Yu helped Gongsun Zan to attack Jizhou." : 6)("relationship" : "Gongsun Zan" : "Zhang Fei" : "Ally" : "Zhang Fei helped Gongsun Zan to attack Jizhou." : 6)("relationship" : "Han Fu" : "Guan Chun" : "Dispatched" : "Han Fu sent Guan Chun to invite Yuan Shao." : 7)("relationship" : "Han Fu" : "Geng Wu" : "Subordinate" : "Geng Wu was Han Fu's chief secretary, and he dissuaded Han Fu from asking Yuan Shao to co-govern the state." : 7)("relationship" : "Geng Wu" : "Yan Liang" : "Hostile" : "Yan Liang immediately killed Geng Wu." : 9)("relationship" : "Guan Chun" : "Wen Chou" : "Hostile" : "Wen Chou killed Guan Chun." : 9)("relationship" : "Yuan Shao" : "General Fenwei" : "Appoint" : "After Yuan Shao entered Jizhou, he appointed Han Fu as General Fenwei." : 7)("relationship" : "Yuan Shao" : "Tian Feng" : "Shared the responsibility of state affairs" : "After Yuan Shao entered Jizhou, Tian Feng shared the responsibility of state affairs." : 7)("relationship" : "Yuan Shao" : "Ju Su" : "Shared the responsibility of state affairs" : "After Yuan Shao entered Jizhou, Ju Su shared the responsibility of state affairs." : 7)("relationship" : "Yuan Shao" : "Xu You" : "Shared the responsibility of state affairs" : "After Yuan Shao entered Jizhou, Xu You shared the responsibility of state affairs." : 7)("relationship" : "Han Fu" : "Zhang Miao" : "Flee" : "Han Fu abandoned his family and went to Chenliu governor Zhang Miao." : 6)("relationship" : "Gongsun Zan" : "Gongsun Yue" :"Brothers" : "Gongsun Yue is Gongsun Zan's younger brother." : 9)("relationship" : "Gongsun Yue" : "Prime Minister Dong" : "Hostile" : "Gongsun Yue was shot to death by Prime Minister Dong's generals." : 8)("relationship" : "Gongsun Zan" : "Yuan Shao" : "Hostile" : "Gongsun Zan and Yuan Shao were hostile over the issue of Jizhou." : 8)("relationship" : "Gongsun Zan" : "Pan River" : "Battle" : "Gongsun Zan and Yuan Shao's armies fought on the Pan River." : 7)("relationship" : "Yuan Shao" : "Pan River" : "Battle" : "Gongsun Zan and Yuan Shao's armies fought on the Pan River." : 7)**
import reimport pandas as pd # Extract structured data using regular expressions pattern = r'''\( # Match opening bracket "relationship"\s*:\s* # Fixed prefix "([^"]+)"\s*:\s* # Capture group 1: source (matches any character except ")"([^"]+)"\s*:\s* # Capture group 2: target"([^"]+)"\s*:\s* # Capture group 3: type"((?:[^"]|\\")*)"\s*:\s* # Capture group 4: description (allows escaped quotes) (\d+) # Capture group 5: weight (number)\) # Match closing bracket'''result_matches = []for text in results: # Find all matches using regular expressions (enable verbose mode and ignore whitespace) matches = re.findall(pattern, text, re.VERBOSE) result_matches.extend(matches)df = pd.DataFrame(result_matcheget', 'type', 'description', 'weight'])
import networkx as nximport matplotlib.pyplot as plt# Create a knowledge graphG = nx.Graph()for _, row in df.iterrows(): G.add_edge(row['source'], row['target'], label=row['type'], weight=row['weight'])# Draw nodes (entities) and edges (relationships) and their labels # Visualize the knowledge graphpos = nx.spring_layout(G, seed=42, k=0.9)labels = nx.get_edge_attributes(G, 'label')plt.figure(figsize=(20, 10))nx.draw(G, pos, with_labels=True, font_size=10, node_size=700, node_color='lightblue', edge_color='gray', alpha=0.6)nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=8, label_pos=0.3, verticalalignment='baseline')plt.title('Relation for SanGuo')plt.show()