使用 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"
  }
]

代码解释:

  1. 使用 fs.readFileSync 读取实体.txt 和关系.txt 文件的内容,并使用 utf-8 编码解析。
  2. 使用 split(' ') 将文本内容按行分割成数组。
  3. 循环遍历实体数组,将每行数据解析成 { id, name } 对象。
  4. 循环遍历关系数组,将每行数据解析成 { entity1Id, entity2Id, type } 对象。
  5. 使用 entities.find 方法根据 entity1Identity2Id 从实体数组中找到对应的实体对象。
  6. 将最终的关系数据以 JSON 格式写入 file.txt 文件中。

总结:

本示例展示了如何使用 Node.js 中的 fs 模块读取文件、处理数据并写入文件。该方法可用于提取不同类型数据之间的关系,并进行进一步的分析和处理。

Node.js 读取文件并提取关系信息:实战教程

原文地址: https://www.cveoy.top/t/topic/mV2Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录