gpt4 book ai didi

javascript - Google Docs Apps 脚本 getBackgroundColor(Offset)

转载 作者:行者123 更新时间:2023-11-30 10:57:55 25 4
gpt4 key购买 nike

假设我在 Google 文档中有一些句子。仅以一句话为例:

"My house is on fire"

我实际上改变了背景颜色,所以每个动词都是红色的,每个名词都是蓝色的。现在我想列出所有动词和另一个名词列表。不幸的是 getBackgroundColor() 似乎只适用于段落而不适用于单个单词。

我的想法是,做这样的事情(我还没有时间考虑如何做循环,但这不是重点):

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();

var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.

Logger.log(colorVar);
}

我得到的错误信息是这样的:

"The function getBackgroundColor in the text object couldn't be found"

感谢任何帮助、提示或评论!

最佳答案

  • 您想从段落中检索文本。
  • 您想从检索到的文本中检索每个词以及每个词的背景颜色。
    • 在这种情况下,颜色是不是 getForegroundColor() 的背景色。
  • 您想使用 Google Apps 脚本实现这一目标。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能的答案之一。首先,你的错误原因是 getBackgroundColor() 是 Class Text 的方法。在您的脚本中,getBackgroundColor() 用于字符串值。由此,错误发生。

在这个答案中,为了实现您的目标,扫描从段落中检索到的文本的每个字符,并且可以检索每个词和每个词的背景颜色。

示例脚本:

function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
  • 当您运行脚本时,将解析第 1 段的文本。你可以看到 res 作为一个对象的结果。
  • 在此示例脚本中,第 1 段用作测试用例。所以如果你想从其他段落中获取值,请修改脚本。

引用资料:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

关于javascript - Google Docs Apps 脚本 getBackgroundColor(Offset),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com