如何在 python 中打印段落的粗体列表编号?

问题描述 投票:0回答:0

我在 MS Word 文档 (.docx) 中有此文本:

    1. best animal is :
    a. cat
    **b. dog**
    c. snake
    2. second best animal is:
    a. rhino
    b. tiger
    **c. puma**

dog 和 puma 是粗体文本,并且是包含大量此类问题的 word 文件中的正确答案。

现在我正在尝试使用 python 循环遍历文本内容,识别粗体段落并将其作为正确答案输出到 json。

我的问题是,虽然我可以打印粗体标识文本,因为它在 word 中的样式显然是标题 1,但我无法在列表中打印分配给它的字母

例如我可以在 json text=dog , text=puma 中打印,但不能打印 text=b。狗,文本=c。彪马

这是我现在使用的代码:

import docx
import jsonpickle

doc_file = docx.Document('C:/Users/Admin/Downloads/test.docx')
json_output = []
for paragraph in doc_file.paragraphs:
    if paragraph.style.name.startswith('Heading 1') and paragraph.style.font.bold:
        json_output.append({'text': paragraph.text, 'bold': True})
   

json_string = jsonpickle.encode(json_output)

print(json_string)

任何人都可以建议解决方案吗?

python python-docx
© www.soinside.com 2019 - 2024. All rights reserved.