Section Word Count in Google Docs

馋奶兔 提交于 2019-12-11 12:45:13

问题


Is it possible for a Google Docs add-on to count word per heading (section)? The following image shows what I want.

Is there a way to display this kind of word count information in a sidebar or any other way?


回答1:


Here is a script that does this. In Google Docs, headings are a kind of paragraph distinguished by their getHeading() attribute. There are thus 9 levels of paragraphs: title, subtitle, h1... h6, and normal.

The script first finds the level of each paragraph and the word count of each paragraph. Then, for each paragraph, it loops over all subsequent "normal" paragraphs, adding their word counts; this stops when another paragraph of equal or higher level is reached.

My understanding that the words in headings themselves should not be included in word counts, but that can be changed if desired.

Since this is not an add-on, there is no sidebar to display information in. I just append the results at the end, copying each heading there and appending (X words) to its text. It looks like this:

Book title (108 words)
 Chapter 1 (54 words)
  Section 1 (15 words)
  Section 2 (20 words)
 Chapter 2 (54 words)
  Section 1 (54 words)
   Subsection 1 (31 words)
   Subsection 2 (13 words)

In my sample text, Chapter 1 has some "intro" normal text before its first section, which is why its word count is higher than the sum of word counts of its two sections.

Script:

function countPerSection() {                
  var body = DocumentApp.getActiveDocument().getBody();
  var para = body.getParagraphs();
  var levels = para.map(function(p) {
    return [DocumentApp.ParagraphHeading.TITLE, 
            DocumentApp.ParagraphHeading.SUBTITLE, 
            DocumentApp.ParagraphHeading.HEADING1,
            DocumentApp.ParagraphHeading.HEADING2,
            DocumentApp.ParagraphHeading.HEADING3,
            DocumentApp.ParagraphHeading.HEADING4,
            DocumentApp.ParagraphHeading.HEADING5,
            DocumentApp.ParagraphHeading.HEADING6,
            DocumentApp.ParagraphHeading.NORMAL].indexOf(p.getHeading());
  });
  var paraCounts = para.map(function (p) {
    return p.getText().split(/\W+/).length;
  });

  var counts = [];
  for (var i = 0; i < para.length; i++) {
    var count = 0;
    for (var j = i+1; j < para.length; j++) {
      if (levels[j] <= levels[i]) {
        break;
      }
      if (levels[j] == 8) {
        count += paraCounts[j];
      }
    }
    counts.push(count);
  }

  for (var i = 0; i < para.length; i++) {
    if (levels[i] < 8) {
      body.appendParagraph(para[i].copy()).appendText(" (" + counts[i] + " words)");
    }
  }
}


来源:https://stackoverflow.com/questions/47954341/section-word-count-in-google-docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!