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')
我的具体问题是:
我怎样才能摆脱空白的第一列?
我不知道为什么它一直出现,但它确实......提前谢谢你帮助我!
解决方案
第一列是从初始表创建开始的,它是空白的,因为您在编写每个项目之前都创建了一个新列。所以你需要这样的东西来“用完”第一个单词的第一列,然后只创建新列:
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
...
推荐阅读
- sql - 使用游标循环更新多个表(SQL Server)
- python-3.x - 了解 lambda 函数排序
- c++ - 由并发无序映射查找线程调用的函数是否安全?
- mysql - MYSQL:错误代码:1054。“where 子句”中的未知列
- c++11 - 初始化 GTest const 类成员
- eclipse - 无法将 Eclipse 项目共享到新的 GIT 存储库,因为资源已存在
- angular - RxJs 在第一次 Emit 时跳过示例,等待一个 Observable 完成
- c++ - 使用 Mutex 挂起程序
- asp.net-core - 使用 ASP.NET Core 2.1 的本地化页面名称
- php - Wordpress 查询自定义帖子类型新增功能