Python-docx - how to restart list inscription

I am automating the process of creating a Word document using the python-docx module. In particular, I am creating a multiple choice test in which questions are numbered 1., 2., 3., ... and for each question there are 4 answers that should be marked as A., B., C., and D I used the style to create a numbered list and a list of letters. However, I do not know how to restart the letters. For example, the answers to the second question will vary from E., F., G., H. Does anyone know how to restart the inscription in A? I could manually specify the inscription in the response line, but I'm wondering how to do this with the stylesheet. Thank.

+5
source share
2 answers

The short answer is that this is not yet supported in python-docx, but we could provide you with a workaround if you ask about this issue in the Github problem list for the project: https://github.com/python-openxml/ python-docx / issues / 25

This particular operation is much more difficult in the Word than I could have imagined. I believe that this is due to the need to maintain a certain backward compatibility on so many versions for a couple of three decades of Word.

, , . / . , , , . , . , , /.

:

  • ,
  • ,

, , , , . API, , , , API, . , , , , .

, . , , .

+4

(# 582), . , , XML, numbering WML. @scanny , xmlchemy - XML, , . , , :

 #!/usr/bin/python

from docx import Document
from docx import oxml


d = Document()


"""
1. Create an abstract numbering definition for a multi-level numbering style.
"""
numXML = d.part.numbering_part.numbering_definitions._numbering
nextAbstractId = max([ J.abstractNumId for J in numXML.abstractNum_lst ] ) + 1
l = numXML.add_abstractNum()
l.abstractNumId = nextAbstractId
m = l.add_multiLevelType()
m.val = 'multiLevel'


"""
2. Define numbering formats for each (zero-indexed)
    level. N.B. The formatting text is one-indexed.
    The user agent will accept up to nine levels.
"""
formats = {0: "decimal", 1: "upperLetter" }
textFmts = {0: '%1.', 1: '%2.' }
for i in range(2):
    lvl = l.add_lvl()
    lvl.ilvl = i
    n = lvl.add_numFmt()
    n.val = formats[i]
    lt = lvl.add_lvlText()
    lt.val = textFmts[i]

"""
3. Link the abstract numbering definition to a numbering definition.
"""
n = numXML.add_num(nextAbstractId)

"""
4. Define a function to set the (0-indexed) numbering level of a paragraph.
"""
def set_ilvl(p,ilvl):
    pr = p._element._add_pPr()
    np = pr.get_or_add_numPr()
    il = np.get_or_add_ilvl()
    il.val = ilvl
    ni = np.get_or_add_numId()
    ni.val = n.numId
    return(p)

"""
5. Create some content
"""
for x in [1,2,3]:
    p = d.add_paragraph()
    set_ilvl(p,0)
    p.add_run("Question %i" % x)
    for y in [1,2,3,4]:
        p2 = d.add_paragraph()
        set_ilvl(p2,1)
        p2.add_run("Choice %i" % y)


d.save('test.docx')
0

Source: https://habr.com/ru/post/1539111/


All Articles