以下是修改后的完整代码,包含角色关系图生成的GML输出功能。主要修改点集中在角色关系分析和GML文件生成部分。
1. 添加角色关系分析类 CharacterRelationshipAnalyzer.java
package com.novel.analyzer;
import com.novel.analyzer.entity.Character;
import com.novel.analyzer.utils.TitleDictionary;
import com.hankcs.hanlp.seg.common.Term;
import java.util.*;
import java.util.stream.Collectors;
public class CharacterRelationshipAnalyzer {
private Map<String, Map<String, Integer>> cooccurrenceMatrix;
private Map<String, Set<String>> relationshipTypes;
public CharacterRelationshipAnalyzer() {
this.cooccurrenceMatrix = new HashMap<>();
this.relationshipTypes = new HashMap<>();
}
public void analyzeRelationships(List<Character> characters, String[] chapters) {
for (int chapIdx = 0; chapIdx < chapters.length; chapIdx++) {
analyzeChapter(chapters[chapIdx], characters, chapIdx);
}
// 计算关系权重
calculateRelationshipWeights(characters);
}
private void analyzeChapter(String chapter, List<Character> characters, int chapterIdx) {
List<Term> terms = HanLP.segment(chapter);
Map<String, Integer> currentCharacters = new HashMap<>();
for (int i = 0; i < terms.size(); i++) {
Term term = terms.get(i);
String name = getCharacterName(term, terms, i);
if (name != null) {
String mainName = getMainName(characters, name);
if (mainName != null) {
currentCharacters.put(mainName, currentCharacters.getOrDefault(mainName, 0) + 1);
}
}
}
// 记录共现关系
recordCooccurrences(currentCharacters);
}
private String getCharacterName(Term term, List<Term> terms, int index) {
String word = term.word;
// 检查前后文是否有称谓
if (index > 0) {
String prevWord = terms.get(index-1).word;
if (TitleDictionary.isTitle(prevWord)) {
return prevWord + word;
}
}
return word;
}
private String getMainName(List<Character> characters, String name) {
return characters.stream()
.filter(c -> c.getMainName().equals(name) || c.getAliases().contains(name))
.findFirst()
.map(Character::getMainName)
.orElse(null);
}
private void recordCooccurrences(Map<String, Integer> currentCharacters) {
List<String> presentChars = new ArrayList<>(currentCharacters.keySet());
for (int i = 0; i < presentChars.size(); i++) {
for (int j = i + 1; j < presentChars.size(); j++) {
String charA = presentChars.get(i);
String charB = presentChars.get(j);
cooccurrenceMatrix.computeIfAbsent(charA, k -> new HashMap<>())
.merge(charB, 1, Integer::sum);
cooccurrenceMatrix.computeIfAbsent(charB, k -> new HashMap<>())
.merge(charA, 1, Integer::sum);
}
}
}
private void calculateRelationshipWeights(List<Character> characters) {
Map<String, Integer> totalOccurrences = characters.stream()
.collect(Collectors.toMap(
Character::getMainName,
c -> c.getTotalFrequency()
));
cooccurrenceMatrix.forEach((charA, relations) -> {
int totalA = totalOccurrences.get(charA);
relations.forEach((charB, count) -> {
int totalB = totalOccurrences.get(charB);
double pmi = calculatePMI(count, totalA, totalB, chapters.length);
relations.put(charB, (int) (pmi * 100)); // 转换为整数权重
});
});
}
private double calculatePMI(int cooccur, int totalA, int totalB, int totalChapters) {
double probA = (double) totalA / totalChapters;
double probB = (double) totalB / totalChapters;
double probCooccur = (double) cooccur / totalChapters;
return Math.max(0, Math.log(probCooccur / (probA * probB)));
}
public Map<String, Map<String, Integer>> getRelationshipNetwork() {
return cooccurrenceMatrix;
}
public void saveAsGML(String outputPath, List<Character> characters) throws IOException {
try (FileWriter fw = new FileWriter(outputPath)) {
fw.write("graph [\n");
fw.write(" directed 0\n");
// 写入节点
Set<String> allChars = new HashSet<>();
characters.forEach(c -> allChars.add(c.getMainName()));
for (String charName : allChars) {
fw.write(String.format(" node [\n id \"%s\"\n label \"%s\"\n ]\n",
charName, charName));
}
// 写入边
for (Map.Entry<String, Map<String, Integer>> entry : cooccurrenceMatrix.entrySet()) {
String source = entry.getKey();
for (Map.Entry<String, Integer> relation : entry.getValue().entrySet()) {
String target = relation.getKey();
int weight = relation.getValue();
fw.write(String.format(" edge [\n" +
" source \"%s\"\n" +
" target \"%s\"\n" +
" weight %d\n" +
" ]\n",
source, target, weight));
}
}
fw.write("]\n");
}
}
}
2. 修改主程序 NovelAnalyzer.java 集成关系分析
package com.novel.analyzer;
import com.novel.analyzer.entity.Character;
import com.novel.utils.FileUtils;
import java.io.IOException;
import java.util.List;
public class NovelAnalyzer {
public static void main(String[] args) throws IOException {
// 参数解析(保持不变)
Map<String, String> params = parseArgs(args);
String inputPath = params.getOrDefault("-input", "src/main/resources/input.txt");
String outputPath = params.getOrDefault("-output", "src/main/resources/output");
// 1. 读取并预处理文本
String novelText = FileUtils.readFile(inputPath);
String cleanedText = NovelPreprocessor.preprocess(novelText);
String[] chapters = cleanedText.split("\n\n");
// 2. 提取角色
CharacterExtractor extractor = new CharacterExtractor();
List<Character> characters = extractor.extractCharacters(cleanedText);
// 3. 分析角色关系
CharacterRelationshipAnalyzer relationshipAnalyzer = new CharacterRelationshipAnalyzer();
relationshipAnalyzer.analyzeRelationships(characters, chapters);
// 4. 保存GML文件
String gmlFilePath = outputPath + "/character_network.gml";
relationshipAnalyzer.saveAsGML(gmlFilePath, characters);
System.out.println("角色关系网络已保存到:" + gmlFilePath);
}
// ... 参数解析方法保持不变 ...
}
3. 更新 pom.xml 添加GML依赖(可选)
如果需要更复杂的GML处理,可以添加以下依赖:
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.5.1</version>
</dependency>
4. 运行分析并生成GML
# 编译打包
mvn clean package
# 运行分析(使用测试文件)
java -jar target/NovelAnalyzer-1.0-SNAPSHOT-jar-with-dependencies.jar \
-input src/main/resources/input.txt \
-output analysis_results
# 检查输出文件
analysis_results/
├── character_network.gml
└── cleaned_output.txt
GML文件示例
生成的character_network.gml文件内容示例:
graph [
directed 0
node [
id "张三"
label "张三"
]
node [
id "李四"
label "李四"
]
edge [
source "张三"
target "李四"
weight 42
]
edge [
source "李四"
target "王五"
weight 28
]
]
可视化步骤
- 使用Gephi打开
character_network.gml
- 应用Force Atlas 2布局
- 根据
weight属性设置边宽度
- 按角色重要度设置节点大小
- 导出为PDF/PNG格式
优化建议:
-
关系类型扩展:
- 在
CharacterRelationshipAnalyzer中添加情感分析
- 识别对话中的情感倾向(需集成情感分析库)
-
权重优化:
- 添加PMI(互信息)计算
- 考虑角色在章节中的位置(开头/结尾出现更重要)
-
性能优化:
- 对长篇小说使用分块处理
- 添加多线程支持(使用Java Stream并行处理)
-
可视化增强:
- 添加角色属性到节点(如性别、身份)
- 使用不同颜色表示关系类型
示例扩展代码(添加PMI计算):
private double calculatePMI(int cooccur, int totalA, int totalB, int totalChapters) {
double probA = (double) totalA / totalChapters;
double probB = (double) totalB / totalChapters;
double probCooccur = (double) cooccur / totalChapters;
return Math.max(0, Math.log(probCooccur / (probA * probB)));
}
现在运行程序后,您将得到包含角色关系网络的GML文件,可以直接用于网络可视化工具(如Gephi、Cytoscape)进行分析和可视化。