Search code examples
pythonregexcountingpython-docx

How to count number of found elements in docx with python?


I've found some sentences with regex in .docx file and printed matches with this code:

import re

from docx import Document

document = Document('Алтайский край.docx')

reg542 = re.compile(r"(?i)Доля записей на прием к врачу, совершенных гражданами дистанционно.*"
                    r"|(?i)Доля граждан, у которых сформированы интегрированные электронные медицинские карты.*"
                    r"|(?i)Доля граждан, находящихся на диспансерном наблюдении.*"
                    r"|(?i)Доля медицинских организаций.*"
                    r"|(?i)Доля врачебных консилиумов.*"
                    r"|(?i)Доля консультаций.*"
                    r"|(?i)Доля граждан..которым доступны врачебные.*"
                    r"|(?i)Доля приобретаемых за бюджетные.*")

for table in document.tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                if reg542.search(paragraph.text):
                    print(paragraph.text)

And now I want to count how many matches were found, but i don't know how, because len() and .count are not working.


Solution

  • This helped me

    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    if reg542.search(paragraph.text):
                        print(paragraph.text)