| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- /**
- * 步骤:
- * 1. 创建startGenerateDialogJson()函数
- * 2. 创建变量resultDialogJsonPath用来接收外部传入的输出目录
- * 3. 遍历sortDialogTxtResultArr,依次把txt文件按照下面json例子,把对话内容分门别类做成json字符串
- {
- "dialogues": [
- {
- "check1": [
- "是石田吗?远道而来辛苦你了"
- ]
- },
- {
- "check2": [
- "现在的大学生好像都喜欢住居民楼或者公寓",
- "所以我还担心没有人愿意来这里寄宿呢"
- ]
- },
- {
- "check3": [
- "房间真是整洁啊"
- ]
- },
- {
- "check4": [
- "是啊以前这里是我的独生女小忍住的房间…"
- ]
- },
-
- {
- "check5": [
- "咦…那不就等于是我霸占了她的房问吗…这不太好吧…"
- ]
- },
- {
- "check6": [
- "没关系的原本就是专门简绘别人寄宿的房间只是后来没人来租我家就没做这门生意就让小忍住这个房问了",
- "原来是这样啊…"
- ]
- }
- ],
- "total_count": 7
- }
- *4. 把json字符串保存为resultDialogJsonPath文件
- */
- import fs from 'fs';
- import path from 'path';
- import { fileURLToPath } from 'url';
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = path.dirname(__filename);
- /**
- * 步骤1: 创建startGenerateDialogJson()函数
- * @param {Array<Array<string>>} sortDialogTxtResultArr - 步骤3: txt文件路径二维数组(外部传入)
- * @param {string} resultDialogJsonPath - 步骤2: 输出JSON文件路径(外部传入)
- * @returns {string} 生成的JSON文件路径
- */
- function startGenerateDialogJson(sortDialogTxtResultArr, resultDialogJsonPath) {
- try {
- console.log('🚀 开始生成对话JSON流程...');
-
- // 步骤2: 创建变量resultDialogJsonPath用来接收外部传入的输出目录
- console.log('\n📄 步骤2: 验证输出JSON文件路径参数');
- if (!resultDialogJsonPath) {
- throw new Error('步骤2失败: resultDialogJsonPath 参数不能为空');
- }
- // 确保输出目录存在
- const outputDir = path.dirname(resultDialogJsonPath);
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir, { recursive: true });
- }
- console.log(`✅ 输出JSON文件路径: ${resultDialogJsonPath}`);
-
- // 步骤3: 遍历sortDialogTxtResultArr,依次把txt文件按照json例子,把对话内容分门别类做成json字符串
- console.log('\n📖 步骤3: 开始遍历txt文件二维数组并读取内容...');
-
- if (!sortDialogTxtResultArr || !Array.isArray(sortDialogTxtResultArr)) {
- throw new Error('步骤3失败: sortDialogTxtResultArr 必须是一个二维数组');
- }
-
- const dialogues = [];
- let totalCount = 0;
-
- // 遍历二维数组(外层数组按check顺序)
- for (let checkIndex = 0; checkIndex < sortDialogTxtResultArr.length; checkIndex++) {
- const checkTxtPaths = sortDialogTxtResultArr[checkIndex];
- const checkName = `check${checkIndex + 1}`;
-
- console.log(`\n 📁 处理 ${checkName} (${checkTxtPaths.length} 个txt文件)`);
-
- if (!Array.isArray(checkTxtPaths) || checkTxtPaths.length === 0) {
- console.log(` ⚠️ ${checkName} 没有txt文件,跳过`);
- continue;
- }
-
- // 读取该check文件夹内所有txt文件的内容
- const checkTexts = [];
-
- for (let i = 0; i < checkTxtPaths.length; i++) {
- const txtPath = checkTxtPaths[i];
-
- console.log(` 📄 [${i + 1}/${checkTxtPaths.length}] 读取: ${path.basename(txtPath)}`);
-
- if (!fs.existsSync(txtPath)) {
- console.log(` ⚠️ txt文件不存在,跳过: ${txtPath}`);
- continue;
- }
-
- try {
- const txtContent = fs.readFileSync(txtPath, 'utf-8').trim();
-
- if (txtContent.length > 0) {
- checkTexts.push(txtContent);
- totalCount++;
- console.log(` ✅ 读取成功: ${txtContent.length} 字符`);
- if (txtContent.length <= 50) {
- console.log(` 内容: ${txtContent}`);
- } else {
- console.log(` 内容预览: ${txtContent.substring(0, 50)}...`);
- }
- } else {
- console.log(` ⚠️ txt文件为空,跳过`);
- }
- } catch (error) {
- console.log(` ⚠️ 读取txt文件失败,跳过: ${error.message}`);
- }
- }
-
- // 如果该check有文本内容,添加到dialogues数组
- if (checkTexts.length > 0) {
- const dialogueItem = {
- [checkName]: checkTexts
- };
- dialogues.push(dialogueItem);
- console.log(` ✅ ${checkName}: 已添加到dialogues (${checkTexts.length} 条文本)`);
- } else {
- console.log(` ⚠️ ${checkName}: 没有有效文本内容,跳过`);
- }
- }
-
- // 构建JSON对象
- const jsonData = {
- dialogues: dialogues,
- total_count: totalCount
- };
-
- console.log(`\n📊 JSON数据统计:`);
- console.log(` 对话组数: ${dialogues.length} 个check`);
- console.log(` 总文本数: ${totalCount} 条`);
-
- // 步骤4: 把json字符串保存为resultDialogJsonPath文件
- console.log('\n💾 步骤4: 保存JSON文件...');
- const jsonString = JSON.stringify(jsonData, null, 2);
- fs.writeFileSync(resultDialogJsonPath, jsonString, 'utf-8');
-
- const stats = fs.statSync(resultDialogJsonPath);
- console.log(`✅ JSON文件已保存: ${path.basename(resultDialogJsonPath)} (${Math.round(stats.size / 1024)}KB)`);
-
- console.log('\n🎉 所有步骤完成!');
- console.log(`📄 生成的JSON文件: ${resultDialogJsonPath}`);
- console.log(`📊 包含 ${dialogues.length} 个check文件夹的对话`);
- console.log(`📊 总共 ${totalCount} 条对话文本`);
-
- return resultDialogJsonPath;
-
- } catch (error) {
- console.error(`\n❌ 生成对话JSON失败: ${error.message}`);
- throw error;
- }
- }
- /**
- * 导出函数供外部调用
- */
- export { startGenerateDialogJson };
|