-1

I have an existing word document in the below format.

1. Test Case Specification Identifier

    [test case number] 55-01-01
    [title] Login with default 

    [revision history] 

    2. Test Items
     [objective] 

    3. Execution
    [step 1]    ;# Non-executable description
      [step 1.1]        ;# Executable Step Level 2 or more

I want to open this word document and update the [objective] and [step] with the below value using python.

objective = "This is objective"

Steps = {"step1":["step1.1","step1.2"],"step2":["step2.1"]}

After including the above data, the output document has look like below.


1. Test Case Specification Identifier
[test case number] 55-01-01
[title] Login with default 

[revision history] 

2. Test Items
 [objective] 
This is objective

3. Execution
[step 1]    Step 1
  [step 1.1]    Step 1.1
  [step 1.2]    Step 1.2
[step 2]    Step 2
  [step 2.1]    Step 2.1

Could you please help?

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
premganesh
  • 67
  • 1
  • 9
  • Must you use a dictionary for `Steps = {"step1":["step1.1","step1.2"],"step2":["step2.1"]}`? Can this also be a list? (for easier searching) – chickity china chinese chicken Oct 17 '18 at 19:29
  • In the document steps contain spaces (like `step 1.1`), but the strings in steps do **not** contain spaces (`"step1.1"`). Is this intentional or may the dictionary (or list of `Steps`) be modified to include spaces to match the syntax in the Word Document? – chickity china chinese chicken Oct 17 '18 at 19:31
  • I can use list also in steps. My actually steps will be like "1) Enter URL in the browser 2) Login page appears 3) provide the valid password " I want to put each line into step 1.1, 1.2,1.3 – premganesh Oct 17 '18 at 20:16

1 Answers1

0

Try this:

from docx import Document
import re

document = Document(docx='existing.docx')
objective = "This is objective"

steps = ["step 1", "step 1.1", "step 1.2", "step 2", "step 2.1"]    

# read current document contents
for paragraph in document.paragraphs:

    if '[objective]' in paragraph.text:
        paragraph.text += objective

    for step in steps:
        indent = 1
        if re.search(r"{}\]".format(step), paragraph.text):
            print step, paragraph.text
            if '.' in step:
                indent += 1
            paragraph.text = '{}[{}]\t{}'.format('\t'*indent, step, step.title())
            steps.remove(step)

# add remaining steps not in existing document    
for step in steps:
    indent = 1
    if '.' in step:
        indent += 1
    document.add_paragraph('{}[{}]\t{}'.format('\t'*indent, step, step.title()))

document.save('output.docx')