[英]How can I find the startIndex of a substring in a Google Docs using the the Python API
Following the Google Docs API documentation recommendation , I've created a document template, containing " placeholders " such as {{my_text_goes_here}}
in order to use the replaceAllText
request to substitute the placeholder with my own text.按照 Google Docs API 文档建议,我创建了一个文档模板,其中包含“占位符”,例如{{my_text_goes_here}}
,以便使用replaceAllText
请求将占位符替换为我自己的文本。 So far so good.到现在为止还挺好。
However, not only I want to insert new text, but I also want to format it.但是,我不仅想插入新文本,而且还想对其进行格式化。 My problem is to retrieve the startIndex
of this new text (or of the previous placeholder).我的问题是检索此新文本(或前一个占位符)的startIndex
。 There aren't any find
or locate
request in the API. API 中没有任何find
或locate
请求。
I've tried to retrieve the text of the whole document ( guide here ), find the position of my placeholder in the text, and use it as the startIndex
for the formatting of my new text (using the updateTextStyle
request) .我尝试检索整个文档的文本(此处为指南),找到我的占位符在文本中的位置,并将其用作新文本格式的startIndex
(使用updateTextStyle
请求) 。 Unfortunately, this value is incorrect and the format isn't applied where it should be.不幸的是,这个值是不正确的,格式没有应用到它应该在的地方。 I suppose it might have to do with UTF-16 encoding or some hidden character...我想这可能与 UTF-16 编码或某些隐藏字符有关...
What I'm trying to do is a very basic action but it requires such complex code to achieve that it renders the whole API useless, except for basic invoice combination (which we could already do 20 years ago with Word and Outlook...)我正在尝试做的是一个非常基本的操作,但它需要如此复杂的代码来实现,以至于它使整个 API 变得毫无用处,除了基本的发票组合(我们在 20 年前就可以使用 Word 和 Outlook 做到这一点......)
What am I missing??我错过了什么??
Might not be as basic as you would like it to be, but what you can do:可能不像您希望的那样基本,但您可以做什么:
Use the method documents.get setting fields to body/content/paragraph/elements(startIndex,textRun/content)
.使用方法documents.get将字段设置为body/content/paragraph/elements(startIndex,textRun/content)
。
This will return you a JSON of type:这将返回一个 JSON 类型:
{
"body": {
"content": [
{},
{
"paragraph": {
"elements": [
{
"startIndex": 1,
"textRun": {
"content": "freter"
}
},
{
"startIndex": 7,
"textRun": {
"content": "\n"
}
}
]
}
},
{
"paragraph": {
"elements": [
{
"startIndex": 8,
"textRun": {
"content": "Htrhyt "
}
},
{
"startIndex": 15,
"textRun": {
"content": "{{my_text_goes_here}}"
}
},
{
"startIndex": 36,
"textRun": {
"content": " gtrtry\n"
}
}
]
}
}
]
}
}
Then you can programmaticaly the content of each textRun
against {{my_text_goes_here}}
and retrieve the startIndex
of the matching elements .然后您可以针对{{my_text_goes_here}}
编程方式处理每个textRun
的内容并检索匹配元素的startIndex
。
For the sample above your result would be:对于上面的示例,您的结果将是:
{
"startIndex": 15,
"textRun": {
"content": "{{my_text_goes_here}}"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.