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

时间:2019-06-19 00:16:01

标签: 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

我的具体问题是:

如何摆脱空白的第一列?

我不知道为什么它会不断出现,但是它确实……在此先感谢您对我的帮助!

1 个答案:

答案 0 :(得分:0)

第一列是初始表创建的地方,该列为空白,因为您在写入每个项目之前创建了一个 new 列。因此,您需要这样的操作来“用完”第一个单词的第一列,然后在此之后创建新列:

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
    ...
相关问题