Python自动化小工具

364 阅读2分钟

PDF 转 WROD

pdf2docx简介:Python实现PDF转Word pdf2docx支持Windows和Linux平台,要求Python版本>=3.6。 首先,通过pip安装:

$ pip install pdf2docx
作为Python库使用
from pdf2docx import Converter

pdf_file = '/path/to/sample.pdf'
docx_file = 'path/to/sample.docx'

# convert pdf to docx
cv = Converter(pdf_file)
cv.convert(docx_file) # 默认参数start=0, end=None
cv.close()

# more samples
# cv.convert(docx_file, start=1) # 转换第2页到最后一页
# cv.convert(docx_file, pages=[1,3,5]) # 转换第2,4,6页

其中,startend参数指定转换页码的范围(下标从0开始),默认转换所有页面( start=0, end=None);也可以通过pages指定不连续的页面,例如pages=[1,3,5]

作为命令行工具使用

pdf2docx也可以作为一个命令行工具,直接在命令窗口中使用:

pdf2docx convert /path/to/pdf /path/to/docx

同理可以通过--start--end或者--pages指定页面范围。

效果

PDF

image.png docx

image.png

python读取word文档中的表格内容输出为.json文件

【Python】自动化:读取word提取json并重新排版(已升级支持打印)
python读取word文档中的表格内容

#下载依赖
pip install  python-docx
from docx import Document
import json

filename = 'C:/Users/66929/Documents/WeChat Files/wxid_68kwaczetutg22/FileStorage/File/2023-08/Oracle-HRMS-数据字典.docx'

doc = Document(filename)
tables = doc.tables

data = []

for i in range(len(tables)):
    tb = tables[i]
    tb_rows = tb.rows
    for i in range(len(tb_rows)):
        row_data = []
        row_cells = tb_rows[i].cells
        for cell in row_cells:
            row_data.append(cell.text)
        data.append(row_data)

# Remove \n from cells
for row in data:
    for i in range(len(row)):
        row[i] = row[i].replace('\n', '')

with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)

print("Json file created successfully")

效果

image.png

改进版(获取表格上方的标题,格式要求:标题必须在表格上方,如下图,文档开头第一行就必须是表格对应的标题,原理就是获取段落和表格,将第一个段落和第一个表格对应组装为JSON)

image.png

from docx import Document
import json

filename = 'C:/Users/66929/Documents/WeChat Files/wxid_68kwaczetutg22/FileStorage/File/2023-08/Oracle-HRMS-数据字典.docx'

doc = Document(filename)
tables = doc.tables

paragraphs = [p.text.strip() for p in doc.paragraphs]

data = []

for i in range(len(tables)):
    tb = tables[i]
    title = paragraphs[i] if i < len(paragraphs) else ""
    
    tb_rows = tb.rows
    table_data = []
    for i in range(len(tb_rows)):
        row_data = []
        row_cells = tb_rows[i].cells
        for cell in row_cells:
            row_data.append(cell.text.replace('\n', ''))
        table_data.append(row_data)
    
    data.append({'title': title, 'data': table_data})

with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)

print("Json file created successfully")

效果如下

image.png