【发布时间】:2021-11-17 20:10:07
【问题描述】:
我正在尝试使用 Google Docs API 根据 JSON 文件中的值自动生成文档。
我创建了一个模板 Google Doc,其结构如下:
I went to the shop and bought the following item: {{foodtype}}.
It cost {{price}}.
JSON 看起来像这样:
{
'food':'apples",
'price':'10'
}
因此,使用 Google Docs replaceAllText 方法,我可以使用 Python 脚本来更新文档,如下所示:
def update_doc(food_json,docs)
requests=[
{
'replaceAllText': {
'containsText': {
'text': '{{foodtype}}',
'matchCase': 'true'
},
'replaceText': 'food_json['food']',
}},]
doc_id = 'xxxxxxxxxxxxx'
result = docs.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
这非常有效。文档中的 {{foodtype}} 标记被 JSON 中的字符串替换。
我的问题是,当我想向文档添加多个更新时,我无法执行此操作。有时可能需要添加 5、10 甚至 50 个项目,因此无法手动向模板添加标签。
例如,如果我的 JSON 看起来像这样:
{
{basket:
{'food':'apples','price':'10'},
{'food':'bread', 'price':'15'}
{'food':'bananas', 'price': '5'}
}
etc etc etc
}
我希望能够编写一个 for 循环来遍历 JSON 并为 JSON 中的每个项目编写报告,例如:
I went to the shop and bought the following item: apple.
It cost 10 cents.
I went to the shop and bought the following item: bread.
It cost 15 cents.
I went to the shop and bought the following item: bananas.
It cost 5 cents.
代码如下所示:
requests = []
for f in food_json['basket']:
requests.append(f)
requests=[
{
'replaceAllText': {
'containsText': {
'text': '{{foodtype}}',
'matchCase': 'true'
},
'replaceText': 'f['food']',
}},
'replaceAllText': {
'containsText': {
'text': '{{price}}',
'matchCase': 'true'
},
'replaceText': 'f['price']',
}},
]
*Push the update to the Google docs*
但是这失败了,因为在 for 循环的第一次迭代中,匹配 {{foodtype}} 标记的文本被替换,然后在下一次迭代中没有任何内容可替换。
我不知道如何继续。
我以前使用过 MS Word 和很棒的 python-docx-template 库以这种方式发布文档。可以在 Word 模板中添加 Jinja 标签,然后直接在文档中使用 for 循环来实现我想要的,例如只需将这样的内容放入模板中即可:
{% for b in basket %}
I went to the shop and bought:
{{ b.food }}
The price was:
{{ b.price }}
{% endfor %}
这很好用,但我看不到如何使用 Google Docs API 和 Python 重现相同的结果。有什么建议吗?
【问题讨论】:
标签: python google-docs google-docs-api