Node.js 读取文件并提取关系信息:实战教程
使用 Node.js 提取文件关系信息
本文将展示如何使用 Node.js 读取两个文本文件(实体.txt 和关系.txt),并提取关系.txt 中包含的实体信息,最终写入到 file.txt 文件中。
实体.txt:
1,John
2,Smith
3,Mary
关系.txt:
1,2,friends
2,3,colleagues
代码示例:
const fs = require('fs');
// 读取实体.txt 文件
const entityData = fs.readFileSync('实体.txt', 'utf-8');
const entities = entityData.split('
').map((line) => {
const [id, name] = line.split(',');
return { id, name };
});
// 读取关系.txt 文件
const relationData = fs.readFileSync('关系.txt', 'utf-8');
const relations = relationData.split('
').map((line) => {
const [entity1Id, entity2Id, type] = line.split(',');
const entity1 = entities.find((entity) => entity.id === entity1Id);
const entity2 = entities.find((entity) => entity.id === entity2Id);
return { entity1, entity2, type };
});
// 将关系信息写入 file.txt 文件中
fs.writeFileSync('file.txt', JSON.stringify(relations));
console.log('写入完成');
运行结果:
在同级目录下会生成 file.txt 文件,内容如下:
[
{
"entity1": {
"id": "1",
"name": "John"
},
"entity2": {
"id": "2",
"name": "Smith"
},
"type": "friends"
},
{
"entity1": {
"id": "2",
"name": "Smith"
},
"entity2": {
"id": "3",
"name": "Mary"
},
"type": "colleagues"
}
]
代码解释:
- 使用
fs.readFileSync读取实体.txt 和关系.txt 文件的内容,并使用utf-8编码解析。 - 使用
split(' ')将文本内容按行分割成数组。 - 循环遍历实体数组,将每行数据解析成
{ id, name }对象。 - 循环遍历关系数组,将每行数据解析成
{ entity1Id, entity2Id, type }对象。 - 使用
entities.find方法根据entity1Id和entity2Id从实体数组中找到对应的实体对象。 - 将最终的关系数据以 JSON 格式写入 file.txt 文件中。
总结:
本示例展示了如何使用 Node.js 中的 fs 模块读取文件、处理数据并写入文件。该方法可用于提取不同类型数据之间的关系,并进行进一步的分析和处理。
原文地址: https://www.cveoy.top/t/topic/mV2Z 著作权归作者所有。请勿转载和采集!