2017-06-21 243 views
1

程序在文档中创建一个标题(当前日期),如果该标题已经在文档中,我想避免标题可能出现重复。我的代码创建一个标题,但也重复。我应该在代码中更改该程序避免重复的内容?如何避免python-docx中的重复?

date = datetime.today().strftime('%A, %d. %B %Y') 
document = Document('example.docx') 
def duplicate(document): 
    for paragraph in document.paragraphs: 
     if date not in paragraph.text: 
      document.add_heading(date) 
      document.save('example.docx') 
duplicate(document) 
+1

添加'duplicate(document)'作为代码的最后一行。你已经定义了一个函数,但从来没有调用它 – inspectorG4dget

+0

感谢您的回答。现在它创建一个标题,但也重复。 – BohdanS

回答

1

在这个问题上的许多问题:

  1. 应该是:datetime.date.today().strftime('%A, %d. %B %Y')
  2. 你的代码查找日期在每一段,如果它不存在,该段,它增加了一个标题与日期。这意味着即使你有一个具有日期的段落,你仍然会为没有的段落创建标题,因为if date not in paragraph.text:仍然运行并且将添加标题
  3. document.save('example.docx')只需要在“重做改变它。你不需要每次都保存它。 for paragraph in document.paragraphs:一直没有明显的原因保存最终结果。

如果你想添加一个只有当它不存在于整个文档中的标题,你可以做这样的事情(还有很多其他的方式,但这对我来说似乎更清洁):

if document.element.xml.find(date) == -1: 
    document.add_heading(date) 
document.save('example.docx')