编程语言
首页 > 编程语言> > python-docx删除段落(含回车符)v202111211833

python-docx删除段落(含回车符)v202111211833

作者:互联网

"""python-docx删除段落(含回车符)v202111211833
工作中需要把微信收藏文章复制到docx(仅保留文本),会出现空行及
不需要的单行,于是试写了如次代码。
"""
import pathlib
from docx import Document

docx = Document()
paths = pathlib.Path("d:\\sucai").rglob("*.docx")#限定扩展名以免运行出错
for path in paths:
    doc = Document(path)
    filename = doc.paragraphs[0].text
    for p in doc.paragraphs:
        # 以下3行代码删除小于50个字符的行(含空行)
        if len(p.text) < 50 and p.text != filename:
            CT_P = p._element
            CT_P.getparent().remove(CT_P)
    doc.save('d:\\sucai\\' + filename + '.docx')

标签:docx,python,text,filename,回车符,doc,Document,CT
来源: https://blog.csdn.net/gqtfnnz/article/details/121457662