用dataviewjs查询统计文档的目标字数、当前字数,并生成进度条

一、前置条件

1、下载插件dataview,并打开JavaScript功能
2、下载插件better-word-count

二、效果图

三、代码

文档元数据

---
目标字数: 32
---

文档查询统计

```dataviewjs
const bwc = app.plugins.plugins["better-word-count"].api;
const folderPath = "请输入文件夹路径"; // 替换为您的文件夹路径

// 获取指定文件夹下的所有文件
const files = app.vault.getFiles().filter(file => file.path.startsWith(folderPath));

// 异步获取每个文件的字数和元数据的字数
const tableData = await Promise.all(files.map(async file => {
    const page = dv.page(file.path);
    const targetWordCount = parseInt(page['目标字数']) || 0; // 从元数据中获取目标字数,如果不存在则默认为0

    // 读取文件内容
    const fileContent = await app.vault.cachedRead(file);
    // 去除元数据的字数
    const contentWithoutMetadata = fileContent.split('---').slice(2).join('---');
    // 使用Better Word Count API计算字数
    const wordCount = bwc.getWordCount(contentWithoutMetadata); // 假设API提供了直接计算字符串字数的方法
    const progressPercentage = targetWordCount > 0 ? Math.round((wordCount / targetWordCount) * 100) : 0;
    const progressBar = `<progress max='100' value='${progressPercentage}'></progress><span>${progressPercentage}%</span>`;
    
    // 获取不带扩展名的文件名
    const fileNameWithoutExtension = file.name.replace(/\.[^/.]+$/, "");
    
    return [`[[${fileNameWithoutExtension}]]`, targetWordCount, wordCount, progressBar];
}));

// 创建表格
dv.table([
    "文档",
    "目标字数",
    "当前字数",
    "完成进度"
], tableData);

1 个赞