使用python docx按部分交叉引用的数字编号 [英] Cross-referenceable figure numbers by section with python docx
问题描述
我一直在使用 python-docx 来生成包含符合标准模板的表格和图形的大型文档.我发现了如何使用 https://github.com 使它们可交叉引用/python-openxml/python-docx/issues/359 .但是,这会在每个部分中标记我的数字/表格,从 1 开始,直到下一部分从 1 重新开始.
I've been using python-docx to produce large documents full of tables and figures conforming with a standard template. I have discovered how to make them cross-referenceable using https://github.com/python-openxml/python-docx/issues/359 . However this labels my figures/tables starting at 1 within each section and continuing until the next section where it restarts from 1.
我希望数字取决于部分编号(即第二部分中的第一个数字 = 图 2.1 等).有谁知道这是否可能?
I would like the figure numbers to be dependent on the section number (i.e. 1st figure in 2nd section = Figure 2.1 etc.). Does anyone know if this is possible?
目前编号是由函数产生的:
Currently the numbering is produced by the function:
def Table(paragraph):
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
run = run = paragraph.add_run()
r = run._r
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' SEQ TableMain \* ARABIC \s 1 '
print instrText
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
由以下代码调用,同时填充表格和表格标题和页脚
Called by the following code which also populates the table and table title and footer
table3 = document.add_table(rows=1, cols=1)
table3.cell(0,0).text="Table "
for paragraph in table4.cell(0,0).paragraphs:
paragraph.style = document.styles['Caption']
Table(paragraph)
paragraph.add_run(text="this is the full table name")
row_cells = table3.add_row().cells
call_func_that_makes_actual_table(row_cells[0],...)
row_cells = table3.add_row().cells
row_cells[0].text="Source: ..."
for paragraph in row_cells[0].paragraphs:
paragraph.style = document.styles['Source']
这会产生一个像这个
而我希望表格编号为这个
推荐答案
我自己设法解决了这个问题,解决方案是添加一个进一步的功能:
Managed to work this out myself the solution is adding a further function:
def section(paragraph):
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
run = run = paragraph.add_run()
r = run._r
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' STYLEREF 1 \s '
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
并将调用更改为:
for paragraph in table.cell(1,0).paragraphs:
paragraph.style = document.styles['Caption']
section(paragraph)
paragraph.add_run(text=".")
Figure(paragraph)
paragraph.add_run(text=": this is the full table name")
这篇关于使用python docx按部分交叉引用的数字编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!