如何从 docx 中创建的 table 中删除空白列?
How remove blank column from table created in 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')
结果如下:
我的具体问题是:
如何去掉第一列的空白?
我不知道为什么它一直出现,但它确实...在此先感谢您对我的帮助!
第一列是最初 table 创建的,它是空白的,因为您在编写每个项目之前创建了一个 new 列。所以你需要这样的东西来 "use up" 第一个单词的第一列,然后只创建新的列:
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
...
我写了一本外语发音指南。它包含有关列表中每个单词的信息。我想用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')
结果如下:
我的具体问题是:
如何去掉第一列的空白?
我不知道为什么它一直出现,但它确实...在此先感谢您对我的帮助!
第一列是最初 table 创建的,它是空白的,因为您在编写每个项目之前创建了一个 new 列。所以你需要这样的东西来 "use up" 第一个单词的第一列,然后只创建新的列:
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
...