【问题标题】:How to find and remove blank paragraphs in a Google Document with Google Apps Script?如何使用 Google Apps 脚本在 Google 文档中查找和删除空白段落?
【发布时间】:2017-02-19 02:48:10
【问题描述】:

我正在处理包含数百个空段落的 Google 文档。我想自动删除这些空行。

在 LibreOffice Writer 中,您可以使用查找和替换工具将 ^$ 替换为空,但这在 Google Docs 中不起作用。

My search for ^$ or ^\s*$ returned 0 results even though there should be 3 matches

如何使用 Google Apps 脚本删除空白段落?

我已经尝试过body.findText("^$");,但返回的是null

function removeBlankParagraphs(doc) {
    var body = doc.getBody();
    result = body.findText("^$");

}

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案1】:

    我认为必须有一个最后一个空白段落,但这似乎有效。

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
    
      var paras = body.getParagraphs();
      var i = 0;
    
      for (var i = 0; i < paras.length; i++) {
           if (paras[i].getText() === ""){
              paras[i].removeFromParent()
           }
    }
    }
    

    【讨论】:

    • 有一个问题:脚本会从文档中删除所有图像,因为将它们识别为空段落。这是解决方法:function myFunction() { var body = DocumentApp.getActiveDocument().getBody(); var paras = body.getParagraphs(); var i = 0; for (var i = 0; i &lt; paras.length; i++) { if (paras[i].getText() === ""){ if (paras[i].findElement(DocumentApp.ElementType.INLINE_IMAGE,null) === null) { paras[i].removeFromParent();} } } }
    • @apmouse,您的解决方法似乎足够相关,可以转移到自己的答案中......
    【解决方案2】:

    添加到汤姆的回答和apmouse 的评论,这是一个修改后的解决方案:1)防止删除由图像或水平规则组成的段落; 2) 还删除仅包含空格的段落。

    function removeEmptyParagraphs() {
      var pars = DocumentApp.getActiveDocument().getBody().getParagraphs();
      // for each paragraph in the active document...
      pars.forEach(function(e) {
        // does the paragraph contain an image or a horizontal rule?
        // (you may want to add other element types to this check)
        no_img = e.findElement(DocumentApp.ElementType.INLINE_IMAGE)    === null;
        no_rul = e.findElement(DocumentApp.ElementType.HORIZONTAL_RULE) === null;
        // proceed if it only has text
        if (no_img && no_rul) {
          // clean up paragraphs that only contain whitespace
          e.replaceText("^\\s+$", "")
          // remove blank paragraphs
          if(e.getText() === "") {
            e.removeFromParent();
          }
        }    
      })
    }
    

    【讨论】:

    • 有效但也会从非空白页面中删除空白,因此需要在运行脚本后向页面添加空白。例如,在部分之间通常有空格的 CV 中。
    • 如果是结构化文档,节空间应该由Section Header的定义来控制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多