Build and Visualize Three Kingdoms Character Networks with Python
This article demonstrates how to extract the character relationships from the classic novel Romance of the Three Kingdoms using Python, building entity dictionaries, constructing a co‑occurrence social network with HarvestText and NetworkX, visualizing subgraphs, ranking important figures, detecting communities, and creating an animated view of the network’s evolution over the story.
Introduction
Inspired by a long‑standing interest in natural language processing and social network analysis, the author explores how to combine these fields to uncover the character network hidden within the classic Chinese novel Romance of the Three Kingdoms using Python.
Preparation
First, the full text of the novel is obtained and split into chapters. An entity‑mention dictionary and an entity‑type dictionary are built so that different names referring to the same historical figure (e.g., "刘备", "玄德") can be linked.
chapters = get_sanguo() # list of chapter texts
print(chapters[0][:106])
entity_mention_dict, entity_type_dict = get_sanguo_entity_dict()
print("刘备的指称有:", entity_mention_dict["刘备"])
print("刘备的类型为", entity_type_dict["刘备"])Building the Social Network
HarvestText is used to load the entity dictionaries, segment sentences, and build an entity graph where an edge is added whenever two entities co‑occur within two consecutive sentences.
ht = HarvestText()
ht.add_entities(entity_mention_dict, entity_type_dict) # load model
doc = chapters[0].replace("操", "曹操")
ch1_sentences = ht.cut_sentences(doc)
# create two‑sentence windows
doc_ch01 = [ch1_sentences[i] + ch1_sentences[i+1] for i in range(len(ch1_sentences)-1)]
ht.set_linking_strategy("freq")
G = ht.build_entity_graph(doc_ch01, used_types=["人名"]) # only person namesThe resulting graph contains thousands of nodes and edges. A subgraph of the most connected characters (degree ≥ 5) is visualized.
Analysis
Important characters are identified by degree, PageRank, and betweenness centrality. The top‑20 figures are plotted as bar charts.
page_ranks = pd.Series(nx.algorithms.pagerank(G)).sort_values()
page_ranks.tail(20).plot(kind="barh")
plt.show()
between = pd.Series(nx.betweenness_centrality(G)).sort_values()
between.tail(20).plot(kind="barh")
plt.show()Community Detection
The Louvain algorithm (via the community package) partitions the network into clusters that correspond roughly to the three kingdoms and their major retainers.
import community # python‑louvain
partition = community.best_partition(G)
comm_dict = defaultdict(list)
for person in partition:
comm_dict[partition[person]].append(person)Sample communities are printed and visualized.
Dynamic Network
To illustrate how the social network evolves over the narrative, snapshots are taken every five chapters and combined into an animated GIF using moviepy. Only the most active nodes are kept in each frame.
import moviepy.editor as mpy
from moviepy.video.io.bindings import mplfig_to_npimage
# ... build sliding windows of graphs ...
animation = mpy.VideoClip(make_frame_mpl, duration=duration)
animation.write_gif("./images/三国社交网络变化.gif", fps=1)Conclusion
The tutorial shows that, despite the novel’s ancient language, modern Python tools can automatically construct and analyze a rich social graph, revealing key figures, their influence, and the shifting alliances throughout the story.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
