You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python通过Google Docs API写入带嵌套格式的混合内容?

前提条件
  • 已创建Google服务账户,且拥有目标Google文档ID(doc_ID)。
问题描述

此前仅处理嵌套列表和普通文本两种元素时,参考@Tanaike的建议成功写入Google文档。现需扩展支持更多元素类型,目标内容列表如下:

my_list = [
    "# 一级标题",
    "这是第一行普通文本,无项目列表格式。",
    "* 这是第一个最外层列表项(数字编号)",
    "  * 这是第一个一级缩进列表项(字母编号)",
    "这是最后一行普通文本,无项目列表格式。",
    "# 一级标题",
    "* 这是标题下的第二个最外层列表项(重新开始数字编号)",
    "  * 这是标题下的第二个一级缩进列表项(字母编号)",
    "这是最后一行普通文本,无项目列表格式。",
]
尝试方案

为适配多种列表元素,初步思路是使用for循环结合if条件判断,代码如下:

requests = []
for item in my_list:
    if item.startswith("# "):
        text = item[2:] + '\n'
        end_index = start_index + len(text)
        item_request = heading_request(text, start_index, end_index)
    elif item.startswith("* "):
        text = item[2:] + '\n'
        end_index = start_index + len(text)
        item_request = list_request(text, start_index, end_index)
    elif item.startswith("  * "):
        text = item[4:] + '\n'
        end_index = start_index + len(text)
        item_request = list_request(text, start_index, end_index)
    else:
        text = item + '\n'
        end_index = start_index + len(text)
        item_request = text_request(text, start_index, end_index)

    requests.append(item_request)
    start_index = end_index

其中,heading_request、list_request、text_request需包含所需字段及对应值。为简洁起见,仅列出list_request的代码片段示例:

[
    {"insertText": {"text": list_text, "location": {"index": start_list_index}}},
    {
        "createParagraphBullets": {
            "range": {"startIndex": start_list_index, "endIndex": end_list_index},
            "bulletPreset": "NUMBERED_DECIMAL_ALPHA_ROMAN"
        }
    }
]
预期效果

Google文档中的预期格式

如何通过编程实现,利用Google Docs API向Google文档写入符合要求的嵌套缩进和文本类型?


内容的提问来源于stack exchange,提问作者Ait Paca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:59:59