Search code examples
pythonpython-3.xpandasnumpypython-docx

How to count the row's values in tables in docx file by using python


I had a problem with counting row's values in tables. Here is my details about the problem, I have a word docx file which consist of many tables. I need to count the Total "Test Type" row's values which has "black box testing". I already asked this question but still can't able to execute. In that docx there are many kinds of tables and paragraph. so I got confused that how to retrieve specific tables and count the row's values. The table would be like this First i need to retrieve the Test Case Detail and then I need to count the total no of black box testing. For example my docx consist nearly 300 above tables so It is hard to count the row's values. please help me

I'm using python 3.6 and I have installed docx module as well.

Code I have tried:

from docx import Document

def table_test_automation(table):
    for row in table.rows:
        row_heading = row.cells[9].text
        if row_heading != 'Test Type':
            continue
        Black_box = row.cells[1].text
        return 1 if Black_box == 'Black Box' else 0

    return 0


document = Document('VRRPv3-PEGASUS.docx')
yes_count = 0
for table in document.tables:
    yes_count += table_test_automation(table)
print("Total No Of Black_box:",yes_count)

First i need to retrieve the Test Case Detail and then I need to count the total no of black box testing. For example my docx consist nearly 300 above tables so It is hard to count the row's values. please help me.

Thanks in advance!


Solution

  • Try this:

    doc = Document("sample.docx")
    i = 0 
    for t in doc.tables:
        for ro in t.rows:
            if ro.cells[0].text=="Test Type" and ro.cells[2].text=="Black Box":
                i=i+1
    print("Total Black Box Tests are: ", i)
    

    Input was:

    enter image description here