How to make the column widths dynamic in docx?

2019-08-18 00:01发布

问题:

I have written a pronunciation guide for a foreign language. It has information about each word in a list. I want to use docx to show the pronunciation guide above the original words and the part of speech below the words.

The length of the text between each word varies considerably, as does the difference in length between the pronunciation, word, and part of speech as shown below.

docx forces me to specify a column width, i.e. Inches(.25) when I add a column using table.add_column(Inches(.25)).cells. I tried playing with the autofit object listed here and could not figure out what it actually does.

The desired result looks like this:

pronunciation_1 | pronunciation_2 | pronunciation_3
---------------------------------------------------
word_1          | word_2          | word_3
---------------------------------------------------
part_of_speech_1 | part_of_speech_2|part_of_speech_3

Here's a code example of my attempt to get this to work. I have tried several times solve my questions below but the code I've written either crashes or returns results worse than this:

from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=3,cols=0)
word_1 = ['This', "th is", 'pronoun']
word_2 = ['is', ' iz', 'verb']
word_3 = ['an', 'uh n', 'indefinite article']
word_4 = ['apple.','ap-uh l', 'noun']
my_word_collection = [word_1,word_2,word_3,word_4]
for word in my_word_collection:
    my_word = word[0]
    pronunciation = word[1]
    part_of_speech = word[2]
    column_cells = table.add_column(Inches(.25)).cells
    column_cells[0].text = pronunciation
    column_cells[1].text = my_word
    column_cells[2].text = part_of_speech
document.save('my_word_demo.docx')

Here's what the results look like. This is a screenshot of how my code renders the text in MS Word:

My specific question is:

How can you make the column widths dynamic?

I want the column width to adjust to the longest of the three data points for each word (my_word, pronunciation, or part_of_speech) to that none of the text needs to wrap, and also so there's not unnecessary excessive space around each word. The goal is the document is created and the reader/user doesn't have to adjust the cell widths for it to be readable.

If it helps, the Q/A here says cell width must be set individually. I tried Googling around how to calculate character widths but it seems like there would be a way to handle this in docx that I don't know about.