小白教程

 找回密码
 立即注册
查看: 8806|回复: 2

[已解决]使用python-docx删除word文档中的空行

[复制链接]

1

主题

2

帖子

5

积分

新手上路

Rank: 1

积分
5
发表于 2021-5-7 13:13:25 | 显示全部楼层 |阅读模式
如何使用python-docx删除word文档中的空行(就是只有个换行符的行),我说的删除是在原文档中删除,不是取出有文字的行,再生成新文档,因为原文档中有python-docx不能处理的内容 ,要保持 原样。
最佳答案
2021-5-8 10:24:35
  1. from docx import Document
  2. def delete_paragraph(paragraph):
  3.     p = paragraph._element
  4.     p.getparent().remove(p)
  5.     p._p = p._element = None
  6. # 创建空白文档,并设置样式
  7. myDocument = Document('test1.docx')
  8. # 设置一个空白样式
  9. for num,paragraphs in enumerate(myDocument.paragraphs):
  10.     if paragraphs.text == "":
  11.         print('第{}段是空行段'.format(num))
  12.         paragraphs.clear()  #清除文字,并不删除段落,run也可以,
  13.         delete_paragraph(paragraphs)
  14. myDocument.save('test2.docx')
复制代码
回复

使用道具 举报

0

主题

2

帖子

4

积分

新手上路

Rank: 1

积分
4
发表于 2021-5-8 10:24:35 | 显示全部楼层 &
  1. from docx import Document
  2. def delete_paragraph(paragraph):
  3.     p = paragraph._element
  4.     p.getparent().remove(p)
  5.     p._p = p._element = None
  6. # 创建空白文档,并设置样式
  7. myDocument = Document('test1.docx')
  8. # 设置一个空白样式
  9. for num,paragraphs in enumerate(myDocument.paragraphs):
  10.     if paragraphs.text == "":
  11.         print('第{}段是空行段'.format(num))
  12.         paragraphs.clear()  #清除文字,并不删除段落,run也可以,
  13.         delete_paragraph(paragraphs)
  14. myDocument.save('test2.docx')
复制代码
回复

使用道具 举报

0

主题

3

帖子

6

积分

新手上路

Rank: 1

积分
6
发表于 2021-5-28 22:39:39 | 显示全部楼层
有误删除的情况,一行中只有图没有文字的,也被删除了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 12:42 , Processed in 0.024870 second(s), 25 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表