generate-dialog-json.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /**
  2. * 步骤:
  3. * 1. 创建startGenerateDialogJson()函数
  4. * 2. 创建变量resultDialogJsonPath用来接收外部传入的输出目录
  5. * 3. 遍历sortDialogTxtResultArr,依次把txt文件按照下面json例子,把对话内容分门别类做成json字符串
  6. {
  7. "dialogues": [
  8. {
  9. "check1": [
  10. "是石田吗?远道而来辛苦你了"
  11. ]
  12. },
  13. {
  14. "check2": [
  15. "现在的大学生好像都喜欢住居民楼或者公寓",
  16. "所以我还担心没有人愿意来这里寄宿呢"
  17. ]
  18. },
  19. {
  20. "check3": [
  21. "房间真是整洁啊"
  22. ]
  23. },
  24. {
  25. "check4": [
  26. "是啊以前这里是我的独生女小忍住的房间…"
  27. ]
  28. },
  29. {
  30. "check5": [
  31. "咦…那不就等于是我霸占了她的房问吗…这不太好吧…"
  32. ]
  33. },
  34. {
  35. "check6": [
  36. "没关系的原本就是专门简绘别人寄宿的房间只是后来没人来租我家就没做这门生意就让小忍住这个房问了",
  37. "原来是这样啊…"
  38. ]
  39. }
  40. ],
  41. "total_count": 7
  42. }
  43. *4. 把json字符串保存为resultDialogJsonPath文件
  44. */
  45. import fs from 'fs';
  46. import path from 'path';
  47. import { fileURLToPath } from 'url';
  48. const __filename = fileURLToPath(import.meta.url);
  49. const __dirname = path.dirname(__filename);
  50. /**
  51. * 步骤1: 创建startGenerateDialogJson()函数
  52. * @param {Array<Array<string>>} sortDialogTxtResultArr - 步骤3: txt文件路径二维数组(外部传入)
  53. * @param {string} resultDialogJsonPath - 步骤2: 输出JSON文件路径(外部传入)
  54. * @returns {string} 生成的JSON文件路径
  55. */
  56. function startGenerateDialogJson(sortDialogTxtResultArr, resultDialogJsonPath) {
  57. try {
  58. console.log('🚀 开始生成对话JSON流程...');
  59. // 步骤2: 创建变量resultDialogJsonPath用来接收外部传入的输出目录
  60. console.log('\n📄 步骤2: 验证输出JSON文件路径参数');
  61. if (!resultDialogJsonPath) {
  62. throw new Error('步骤2失败: resultDialogJsonPath 参数不能为空');
  63. }
  64. // 确保输出目录存在
  65. const outputDir = path.dirname(resultDialogJsonPath);
  66. if (!fs.existsSync(outputDir)) {
  67. fs.mkdirSync(outputDir, { recursive: true });
  68. }
  69. console.log(`✅ 输出JSON文件路径: ${resultDialogJsonPath}`);
  70. // 步骤3: 遍历sortDialogTxtResultArr,依次把txt文件按照json例子,把对话内容分门别类做成json字符串
  71. console.log('\n📖 步骤3: 开始遍历txt文件二维数组并读取内容...');
  72. if (!sortDialogTxtResultArr || !Array.isArray(sortDialogTxtResultArr)) {
  73. throw new Error('步骤3失败: sortDialogTxtResultArr 必须是一个二维数组');
  74. }
  75. const dialogues = [];
  76. let totalCount = 0;
  77. // 遍历二维数组(外层数组按check顺序)
  78. for (let checkIndex = 0; checkIndex < sortDialogTxtResultArr.length; checkIndex++) {
  79. const checkTxtPaths = sortDialogTxtResultArr[checkIndex];
  80. const checkName = `check${checkIndex + 1}`;
  81. console.log(`\n 📁 处理 ${checkName} (${checkTxtPaths.length} 个txt文件)`);
  82. if (!Array.isArray(checkTxtPaths) || checkTxtPaths.length === 0) {
  83. console.log(` ⚠️ ${checkName} 没有txt文件,跳过`);
  84. continue;
  85. }
  86. // 读取该check文件夹内所有txt文件的内容
  87. const checkTexts = [];
  88. for (let i = 0; i < checkTxtPaths.length; i++) {
  89. const txtPath = checkTxtPaths[i];
  90. console.log(` 📄 [${i + 1}/${checkTxtPaths.length}] 读取: ${path.basename(txtPath)}`);
  91. if (!fs.existsSync(txtPath)) {
  92. console.log(` ⚠️ txt文件不存在,跳过: ${txtPath}`);
  93. continue;
  94. }
  95. try {
  96. const txtContent = fs.readFileSync(txtPath, 'utf-8').trim();
  97. if (txtContent.length > 0) {
  98. checkTexts.push(txtContent);
  99. totalCount++;
  100. console.log(` ✅ 读取成功: ${txtContent.length} 字符`);
  101. if (txtContent.length <= 50) {
  102. console.log(` 内容: ${txtContent}`);
  103. } else {
  104. console.log(` 内容预览: ${txtContent.substring(0, 50)}...`);
  105. }
  106. } else {
  107. console.log(` ⚠️ txt文件为空,跳过`);
  108. }
  109. } catch (error) {
  110. console.log(` ⚠️ 读取txt文件失败,跳过: ${error.message}`);
  111. }
  112. }
  113. // 如果该check有文本内容,添加到dialogues数组
  114. if (checkTexts.length > 0) {
  115. const dialogueItem = {
  116. [checkName]: checkTexts
  117. };
  118. dialogues.push(dialogueItem);
  119. console.log(` ✅ ${checkName}: 已添加到dialogues (${checkTexts.length} 条文本)`);
  120. } else {
  121. console.log(` ⚠️ ${checkName}: 没有有效文本内容,跳过`);
  122. }
  123. }
  124. // 构建JSON对象
  125. const jsonData = {
  126. dialogues: dialogues,
  127. total_count: totalCount
  128. };
  129. console.log(`\n📊 JSON数据统计:`);
  130. console.log(` 对话组数: ${dialogues.length} 个check`);
  131. console.log(` 总文本数: ${totalCount} 条`);
  132. // 步骤4: 把json字符串保存为resultDialogJsonPath文件
  133. console.log('\n💾 步骤4: 保存JSON文件...');
  134. const jsonString = JSON.stringify(jsonData, null, 2);
  135. fs.writeFileSync(resultDialogJsonPath, jsonString, 'utf-8');
  136. const stats = fs.statSync(resultDialogJsonPath);
  137. console.log(`✅ JSON文件已保存: ${path.basename(resultDialogJsonPath)} (${Math.round(stats.size / 1024)}KB)`);
  138. console.log('\n🎉 所有步骤完成!');
  139. console.log(`📄 生成的JSON文件: ${resultDialogJsonPath}`);
  140. console.log(`📊 包含 ${dialogues.length} 个check文件夹的对话`);
  141. console.log(`📊 总共 ${totalCount} 条对话文本`);
  142. return resultDialogJsonPath;
  143. } catch (error) {
  144. console.error(`\n❌ 生成对话JSON失败: ${error.message}`);
  145. throw error;
  146. }
  147. }
  148. /**
  149. * 导出函数供外部调用
  150. */
  151. export { startGenerateDialogJson };