Aro*_*oon 7 python python-3.x python-docx
我知道这是一个重复的问题,但这些答案对我不起作用.我有一个word文件,它包含一个表,现在我希望该表作为我的python程序的输出.我正在使用python 3.6,我也安装了python -docx.这是我的数据提取代码
from docx.api import Document
document = Document('test_word.docx')
table = document.tables[0]
data = []
keys = None
for i, row in enumerate(table.rows):
text = (cell.text for cell in row.cells)
if i == 0:
keys = tuple(text)
continue
row_data = dict(zip(keys, text))
data.append(row_data)
print (data)
Run Code Online (Sandbox Code Playgroud)
我希望结果在docx文件中看起来完全正确.提前致谢
Ant*_*vBR 11
你的代码对我来说很好.如何将其插入数据框?
import pandas as pd
from docx.api import Document
document = Document('test_word.docx')
table = document.tables[0]
data = []
keys = None
for i, row in enumerate(table.rows):
text = (cell.text for cell in row.cells)
if i == 0:
keys = tuple(text)
continue
row_data = dict(zip(keys, text))
data.append(row_data)
print (data)
df = pd.DataFrame(data)
Run Code Online (Sandbox Code Playgroud)
如何在该表中显示特定的行和列?我们可以使用iloc基于索引提取行和列
# iloc[row,columns]
df.iloc[0,:].tolist() # [5,6,7,8] - row index 0
df.iloc[:,0].tolist() # [5,9,13,17] - column index 0
df.iloc[0,0] # 5 - cell(0,0)
df.iloc[1:,2].tolist() # [11,15,19] - column index 2, but skip first row
Run Code Online (Sandbox Code Playgroud)
等等...
但是,如果您的列有名称(在这种情况下它是数字),您可以这样做:
#df["name"].tolist()
df[1].tolist() # [5,6,7,8] - column with name 1
Run Code Online (Sandbox Code Playgroud)
print(df)
Run Code Online (Sandbox Code Playgroud)
打印,这是我的示例文档中表格的样子.
1 2 3 4
0 5 6 7 8
1 9 10 11 12
2 13 14 15 16
3 17 18 19 20
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7643 次 |
| 最近记录: |