python - 如何从 docx 创建的表中删除空白列?

标签 python python-3.x docx python-docx

我写了一本外语发音指南。它包含有关列表中每个单词的信息。我想用docx在原词上方显示发音指南,在词下方显示词性。

期望的结果如下所示:

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=1)
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]
    pronounciation = word[1]
    part_of_speech = word[2]
    column_cells = table.add_column(Inches(.25)).cells
    column_cells[0].text = pronounciation
    column_cells[1].text = my_word
    column_cells[2].text = part_of_speech
document.save('my_word_demo.docx')

结果如下: Screenshot of how my code renders the text in MS Word 2010

我的具体问题是:

如何去掉第一列空白?

我不知道为什么它不断出现,但它确实......提前感谢您帮助我!

最佳答案

第一列是在初始表创建时出现的,它是空白的,因为您在写入每个项目之前创建了一个列。因此,您需要这样的东西来“用完”第一个单词的第一列,然后仅创建新列:

table = document.add_table(rows=3, cols=1)
for idx, word in enumerate(words):
    column = table.columns[0] if idx == 0 else table.add_column(..)
    cells = column.cells
    ...

关于python - 如何从 docx 创建的表中删除空白列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56658554/

相关文章:

python - 在 tflite Interpreter 中分配张量时出错

python - 您如何操纵范围函数的第三个参数以增加 n 倍?

python - 在python中查找列表的所有子列表

asp.net - 如何在使用Docx dll生成word文档时在标题中添加图像和文本?

vba - 通过 docx 文件宏中的索引以编程方式删除重复节项?

python + google drive : upload xlsx, 转换为google sheet,获取共享链接

python - 如何在单独的列表中拆分字符串中的每个单词

java - Apache POI - 在Word文件中编辑图表数据时,它返回表单中定义的数据

python Pandas : Sorting Columns

python - 使用预定义列表分解行,同时保留现有行的值