如何在docx中使列宽动态化?

2024-06-06 12:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一本外语发音指南。它有关于列表中每个单词的信息。我想用docx来显示原单词上面的发音指南和单词下面的词性。你知道吗

每个单词之间的文本长度差别很大,发音、单词和词性之间的长度差别也很大,如下所示。你知道吗

docx强制我指定列宽,即使用table.add_column(Inches(.25)).cells添加列时Inches(.25)。我试着玩autofit列出的对象here,但搞不清楚它到底做了什么。你知道吗

预期结果如下所示:

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

下面是一个代码示例,我试图让它工作。我已经尝试过多次解决下面的问题,但我编写的代码要么崩溃,要么返回比这更糟糕的结果:

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')

结果是这样的。这是我的代码如何在MS Word中呈现文本的屏幕截图: Code rendered in MS Word showing non-dynamic cell widths

我的具体问题是:

如何使列宽动态化?

我想将列宽调整为每个单词(我的单词、发音或词性)的三个数据点中最长的一个,使所有的文本都不需要换行,这样每个单词周围就不会有多余的空间。目标是创建文档,读者/用户无需调整单元格宽度即可使其可读。你知道吗

如果有帮助,Q/Ahere表示单元格宽度必须单独设置。我试着在google上搜索如何计算字符宽度,但似乎有一种方法可以在docx中处理这个问题,我不知道。你知道吗


Tags: of文本mytablecolumn单词speechword