Search code examples
pythonpython-docx

Extract text and compare cells from table - python docx


I have a program which prints random value from a list in the cells of a table using python docx. The number of tables, cells and rows depend on user input. I need to compare cells of tables before inputing value in the same number cell in another table.

For example.

number_of_tables = 5 #input by user
number_of_rows = 4 #input by user
number_of_cols = 7 #input by user

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

docu = Document()

for tablenum in range(number_of_tables):
    tablename = docu.add_table(rows = number_of_rows, cols = number_of_cols)
    for rowiteration in tablename.rows[0:]:
        for cells in rowiteration.cells:
            cells.text = random.choices(list)

If here cell(0,0) in table 1 has 'a' I don't want to print in 'a' in cell(0,0) of table 2 and further more.


Solution

  • Basically, you want to chose a random value from the list, but exclude one (or more) value(s) - see also this question.

    You should therefore construct another list without the value(s) that you want to exclude - example to exclude the value 'a' from the choice:

    random.choice([s for s in list if s != 'a'])
    

    For your scenario, you will have to exclude all values from the same cell (r,c) in the other tables like this:

    for tablenum in range(number_of_tables):
      tablename = docu.add_table(rows=number_of_rows, cols=number_of_cols)
      for r, rowiteration in enumerate(tablename.rows):
        for c, cells in enumerate(rowiteration.cells):
          exclude = [docu.tables[num].cell(r,c).text for num in range(tablenum)]
          cells.text = random.choice([s for s in list if s not in exclude])