Google Apps 脚本 - 无法读取 Google 文档中段落的粗体属性

Google Apps Script - Cannot read Bold Attribute of a Paragraph in a Google Doc

我正在尝试使用 Apps 脚本从 Google 文档中读取段落的属性。当我读取属性时,一些 BOLD 属性返回为 null。

这是我读取属性的示例脚本。

// 读取此 Google 文档中每个段落的属性并打印所有加粗的段落文本

function readAttributes() {
  var doc = DocumentApp.getActiveDocument(); 
  var body = doc.getBody(); 
  var paras = body.getParagraphs();
  for (var i = 0; i < paras.length; i++){ 
    var paragraph = paras[i];  
    var attribute = paragraph.getAttributes(); 
    if (attribute.BOLD === true) {
      Logger.log(paragraph.getText()); 
    }
  } 
}

这是一个模拟的示例文档: 该脚本位于此 Google 文档的后面。文件 -> 制作副本。

https://docs.google.com/document/d/13FYg8AAk6PX9TEUdgfaT-60Vi5xoQlZ9Moink5guLH0/edit?usp=sharing

我的文档有什么问题?只有问题 18 的属性返回为 BOLD,问题 17 的属性返回为 null。

Google 文档中任何段落的返回属性对象如下所示。

 {
    FONT_SIZE=null, 
    ITALIC=null, 
    HORIZONTAL_ALIGNMENT=null, 
    INDENT_END=null,
    INDENT_START=null, 
    LINE_SPACING=1.0, 
    LINK_URL=null, 
    UNDERLINE=null, 
    BACKGROUND_COLOR=null, 
    INDENT_FIRST_LINE=null, 
    LEFT_TO_RIGHT=true, 
    SPACING_BEFORE=null, 
    HEADING=Normal, 
    SPACING_AFTER=null, 
    STRIKETHROUGH=null, 
    FOREGROUND_COLOR=null, 
    BOLD=null, 
    FONT_FAMILY=Calibri
}

我的 Logger.log() 结果:

预期输出:

  1. 如果您的车辆在驾驶时着火,以下哪项是最有效的行动计划?
  2. 出行前,您需要检查轮胎。哪些问题需要立即采取行动?

结果输出:

  1. 出行前,您需要检查轮胎。哪些问题需要立即采取行动?

显示问题的图像

很明显文档中的问题17有问题,所以它的BOLD属性为空。

在你的样本中,在17. Which of ...的段落中,整段都不是BOLD属性。另一方面,在18. Before taking...的段落中,整段都是BOLD属性。这样,17. Which of ...段落的BOLD属性就变成了null。那么这个修改怎么样呢?我认为您的情况有几个答案。所以请将此视为其中之一。

修改点:

  • 关于每个段落,扫描文本中的每个字符。并检索具有 BOLD 属性的字符。
    • 对于这种情况,它使用isBold()

修改后的脚本:

请修改如下

从:
for (var i = 0; i < paras.length; i++){ 
  var paragraph = paras[i];  
  var attribute = paragraph.getAttributes(); 
  if (attribute.BOLD === true) {
    Logger.log(paragraph.getText()); 
  }
} 
到:
for (var i = 0; i < paras.length; i++) {
  var res = "";
  var paragraph = paras[i];
  var attribute = paragraph.editAsText();
  for (var j = 0; j < attribute.getText().length; j++) {
    if (attribute.isBold(j)) {
      res += attribute.getText()[j];
    }
  }
  if (res.length > 0) {
    Logger.log(res)
  }
}

结果:

  1. Which of the following is the most effective plan of action to take if your vehicle catches fire while you are driving?
  2. Before taking a trip, you need to inspect your tires. Which problems would require immediate action?

注:

  • 在本次修改中,如果句子中包含非BOLD属性的字符,则不检索此类字符。如果所有字符都是 BOLD 属性,则检索整个句子。请注意这一点。

参考:

如果这不是你想要的,我很抱歉。