【问题标题】:Python 3 Beginner - Python Docx String ManipulationPython 3 初学者 - Python Docx 字符串操作
【发布时间】:2017-03-12 02:50:36
【问题描述】:
from docx import Document
import string
c_dic = ['a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','r','s','t','u','v','w','y','z','m']
doc = Document('test3.docx')
firstSen = doc.paragraphs[0].text
indexLetters = 0
while indexLetters < len(c_dic):
    d_dic = c_dic[indexLetters]
    indexLetters += 1
    secondSen = firstSen.replace(d_dic,"")    
    print (secondSen)

#results:
#hello there
#hllo thr 
#hello there
#....

我正在尝试从 text3 文档中删除句子。第一句话是“你好”。我正在尝试运行此脚本并删除该句子。然而,脚本只是删除了句子的一部分,并反复给我“你好”。

*编辑 我计划将此扩展到具有多种外语的单独文档。所以我正在尝试从文档中删除所有英文段落。

【问题讨论】:

  • sencondSen = firstSen.replace(d_dic, "") 它将替换来自 firstSen 的 d_dic 字母并将其存储在 secondSen 但您不会更改 fisrtSen se fisrtSen 将始终保持不变并且循环将运行 26次因为c_dic 26 的长度。现在你可以修改你的逻辑

标签: python python-3.x ms-word python-docx


【解决方案1】:

如果你想删除句子为什么要删除它的字母。可以一次删除整个字符串。

如果你只是想删除第一句话,那么你可以通过像这样切片我们的列表来删除 doc.paragraphs 的第一个元素:

first_sent_removed = doc.paragraphs[1:]

假设你总是想删除第一句话。

假设您宁愿指定字符串并在段落中搜索包含要删除的文本的句子。这将删除坏句子并返回列表中的其他句子

bad_string = '你好'

clean_para = [sent for sent in doc.paragraphs is bad_string not in sent]

【讨论】:

    【解决方案2】:

    ...
    doc.split()
    remove = "words you want to remove".split()

    for I in doc.paragraphs: if I in string: doc.paragraphs.remove(I)

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-09
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      相关资源
      最近更新 更多