首页 > 解决方案 > 使用 python 文档拆分

问题描述

我正在寻找修改当前使用 python-docx 将文本从 .txt 文件导入到 .docx 文件的特定部分的程序。目前我使用 find_replace 功能。我在 github 上发现了一个很棒的项目,但是我很难弄清楚我到目前为止做错了什么。这是项目:

https://github.com/alllexx88/python-docx-split-run

这是我写的:

def insert_run_after(par, run, txt=''):
    """Insert a new run with text {txt} into paragraph after given {run}.

    Returns the newly created run.
    """
    run_2 = par.add_run(txt)
    run._r.addnext(run_2._r)

    return run_2

document = Document('Psychevaltemplate2.docx')
par = document.paragraphs[0]
run = par.runs[0]
background = input("what is the location of the background file?")

input_doc = Document(background)
insert_run_after(par, 5, 'TEST RESULTS:')
output_doc.save("sampleoutput2.docx")

exit()

这是错误:

run._r.addnext(run_2._r)

AttributeError:“int”对象没有属性“_r”

任何帮助将不胜感激。

标签: pythonpython-docx

解决方案


在行中:insert_run_after(par, 5, 'TEST RESULTS:')5作为run参数传递。

也许你是这个意思?

insert_run_after(par, par.runs[5], "TEST RESULTS:")

或者可能:

insert_run_at_position(par, 5, "TEST RESULTS:")

这是该项目中可用的其他功能之一。


推荐阅读