【问题标题】:Extract text and compare cells from table - python docx从表格中提取文本并比较单元格 - python docx
【发布时间】:2020-02-06 11:19:32
【问题描述】:

我有一个程序,它使用 python docx 从表格单元格中的列表中打印随机值。 表格、单元格和行的数量取决于用户输入。 在另一个表格的相同数字单元格中输入值之前,我需要比较表格的单元格。

例如。

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)

如果表 1 中的单元格 (0,0) 有“a”,我不想在表 2 的单元格(0,0) 中的“a”中打印等等。

【问题讨论】:

    标签: python python-docx


    【解决方案1】:

    基本上,您想从list 中选择一个随机值,但排除一个(或多个)值 - 另请参阅this question

    因此,您应该构造另一个没有要排除的值的列表 - 例如从选择中排除值 '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])
    

    【讨论】:

    • 谢谢。我可以从文档中提取上一个表格,但很难指向/提取该表格中的特定单元格以与当前表格单元格进行比较。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2015-01-01
    • 2018-08-13
    相关资源
    最近更新 更多