从 table - python docx 中提取文本并比较单元格
Extract text and compare cells from table - python docx
我有一个程序,它使用 python docx 从 table 的单元格中的列表中打印随机值。
table 的数量、单元格和行数取决于用户输入。
在另一个 table.
的相同数字单元格中输入值之前,我需要比较 tables 的单元格
例如
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)
如果 table 1 中的单元格 (0,0) 具有 'a' 我不想在 [=22 的单元格 (0,0) 中的 'a' 中打印=] 2 以及更多。
基本上,您想从 list
中选择一个随机值,但排除一个(或多个)值 - 另请参见 。
因此,您应该构建另一个没有要排除的值的列表 - 例如从选择中排除值 'a'
:
random.choice([s for s in list if s != 'a'])
对于您的情况,您必须排除其他表中同一单元格 (r,c)
的所有值,如下所示:
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])
我有一个程序,它使用 python docx 从 table 的单元格中的列表中打印随机值。 table 的数量、单元格和行数取决于用户输入。 在另一个 table.
的相同数字单元格中输入值之前,我需要比较 tables 的单元格例如
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)
如果 table 1 中的单元格 (0,0) 具有 'a' 我不想在 [=22 的单元格 (0,0) 中的 'a' 中打印=] 2 以及更多。
基本上,您想从 list
中选择一个随机值,但排除一个(或多个)值 - 另请参见
因此,您应该构建另一个没有要排除的值的列表 - 例如从选择中排除值 'a'
:
random.choice([s for s in list if s != 'a'])
对于您的情况,您必须排除其他表中同一单元格 (r,c)
的所有值,如下所示:
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])