【问题标题】:How to get attributes (Bold, italic etc.) of each word from cell text value in SpreadsheetApp如何从 SpreadsheetApp 中的单元格文本值中获取每个单词的属性(粗体、斜体等)
【发布时间】:2021-05-20 14:43:21
【问题描述】:

我需要 Google Apps 脚本中电子表格单元格中存在的句子中每个单词的属性。

例如,在下图中,单词“神经网络。” 以粗体显示。我想获取句子中每个单词的属性,以识别哪个单词有什么风格。

以下是我用来获取单元格值(文本)的代码。

function getSheetsSelection(e) {
  var text = '';
  var ranges = SpreadsheetApp.getActive().getSelection().getActiveRangeList().getRanges();
  for (var i = 0; i < ranges.length; i++) {
    const range = ranges[i];
    const numRows = range.getNumRows();
    const numCols = range.getNumColumns();
    for (let i = 1; i <= numCols; i++) {
      for (let j = 1; j <= numRows; j++) {
        const cell = range.getCell(j, i);
        if (cell.getValue()) {
          var cellTextStyle = cell.getValues()
        }
      }
    }
  }
}

注意:在这段代码中,在cell 变量中,我们得到了一个名为getTextStyle() 的方法,但它返回的是整个单元格的样式,而不是单个单词。而在DocumentApp 中,我们得到文本,例如作为段落或文本,我们可以遍历所有单词并获取它们的属性。我们可以在 SpreadsheetApp 中执行类似该段落的内容吗?

【问题讨论】:

标签: google-apps-script attributes styles spreadsheet paragraph


【解决方案1】:

Class RichTextValue

Class TextStyle

详细代码:

var sheet     = SpreadsheetApp.getActiveSheet();
var range     = sheet.getRange("B1");
var rich_text = range.getRichTextValue();
var runs      = rich_text.getRuns();

var words_bold = [];

for (var r of runs) {
  var style = r.getTextStyle();
  if (style.isBold()) words_bold.push(r.getText());
}

Logger.log(words_bold);

单行函数:

const bold_words_from = (cell) => 
  SpreadsheetApp.getActiveSheet().getRange(cell).getRichTextValue().getRuns()
  .filter(r=>r.getTextStyle().isBold()).map(r=>r.getText());

Logger.log(bold_words_from("B1"));

输入:

A B
1 Neuron(Node) It is the basis unit of a neural network.
2 Connections It connects one neuron in one layer to another neuron in other layer
3 Bias(Offset) It is an extra input to neurons and int as always 1
4 Input Shape It is the shape of the input matrix we pass to the input layer.

输出:

[ basis , neural network ]

以同样的方式你可以得到斜体(isItalic())等。但它们不是文字。它们是“运行”:

run 是具有相同文本样式的最长不间断子字符串。例如,句子“这个孩子 有两个苹果”。有五个单词和四个运行:[“This”、“kid”、“有两个”、“apples.”]。

我不知道你到底想要获得什么。所以这取决于你将如何使用这些运行,如果这些 运行 应该以某种方式与单词对齐,等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2014-04-29
    • 1970-01-01
    • 2016-06-13
    相关资源
    最近更新 更多