Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向类似于表格单元格的段落添加文本_Python_Logic_Python Docx - Fatal编程技术网

Python 如何向类似于表格单元格的段落添加文本

Python 如何向类似于表格单元格的段落添加文本,python,logic,python-docx,Python,Logic,Python Docx,第一次在SE so上发布,对格式不正确表示歉意。我是python和pythondocx模块的新手,因此我的代码中可能缺少一些基本的东西。本质上,我试图在for循环中包含一个“add_段落”,这样每次循环都会给段落文本添加+1值 我已经能够遍历一个表的单元格,如下所示: document= document(filename.docx) for x in range(0,3): ##creates 3 tables table = document.add_table(rows=3,c

第一次在SE so上发布,对格式不正确表示歉意。我是python和pythondocx模块的新手,因此我的代码中可能缺少一些基本的东西。本质上,我试图在for循环中包含一个“add_段落”,这样每次循环都会给段落文本添加+1值

我已经能够遍历一个表的单元格,如下所示:

document= document(filename.docx)

for x in range(0,3): ##creates 3 tables
     table = document.add_table(rows=3,cols=3)

for y in range(0,3):
     for z in range(0,3):
          tablecells = document.tables[x].rows[y].cells
          tablecells[0].text = 'Column 0, cell %d' % (z)
这段代码的输出会在第一个表的第一列给出类似的内容:

|------------------|--------------|---------|
|Column 0, cell 0  |              |         |
|------------------|--------------|---------|
|Column 0, cell 1  |              |         |
|------------------|--------------|---------|
|Column 0, cell 2  |              |         |
|------------------|--------------|---------|
因此,这种方法非常适用于用已知值填充表

我想知道是否有一种方法可以通过段落而不是表格单元格来实现这一点。我的伪代码如下所示:

for x in range(1,4):
     document.add_paragraph('This is paragraph %d') % (x)
我的预期结果是:

This is paragraph 1

This is paragraph 2

This is paragraph 3
但是,如果尝试运行此代码,则会出现以下错误:

TypeError: unsupported operand type(s) for %: 'Paragraph' and 'int'
我希望我能说清楚,并提前感谢您的帮助和知识

改变这个

for x in range(1,4):
     document.add_paragraph('This is paragraph %d') % (x)

第一段代码尝试在文档的结果上实现%运算符。添加_段落(“这是段落%d”)和x,x应该是错误中提到的段落(对象)


第二部分是您想要的,即对字符串应用%运算符,并用x值替换%d。

这正是我想要的!你能解释一下它为什么工作或者我做错了什么吗?document.add_段落('这是段落%d')%(x)-->在这段代码中,document.add_段落('这是段落%d')首先执行,然后对结果应用%运算符。你想要的是('这是段落%d'%x')首先执行,所以我们将这段代码包装到内部的parantises/bracketAhh好的,这是有意义的。谢谢你澄清这一点。执行代码时出现不理解代码的简单错误。
for x in range(1,4):
     document.add_paragraph('This is paragraph %d' % (x))