Openpyxl 检查关键字,然后修改单元格旁边以包含这些关键字和找到的总数

Openpyxl to check for keywords, then modify next to cells to contain those keywords and total found

我正在使用 python 3.x 和 openpyxl 来解析 excel .xlsx 文件。

对于每一行,我检查列 (C) 以查看这些关键字是否匹配。 如果是这样,我将它们添加到一个单独的列表变量中,并确定匹配了多少关键字。

然后我想将实际关键字添加到下一个单元格中,然后将关键字总数添加到单元格中。这是我遇到问题的地方,实际上是在写结果。

keywords.txt 和 results.xlsx 文件的内容 here

import openpyxl

# Here I read a keywords.txt file and input them into a keywords variable 
# I throwaway the first line to prevent a mismatch due to the unicode BOM
with open("keywords.txt") as f:
    f.readline()
    keywords = [line.rstrip("\n") for line in f]

# Load the workbook
wb = openpyxl.load_workbook("results.xlsx")
ws = wb.get_sheet_by_name("Sheet")

# Iterate through every row, only looking in column C for the keyword match.
for row in ws.iter_rows("C{}:E{}".format(ws.min_row, ws.max_row)):
    # if there's a match, add to the keywords_found list
    keywords_found = [key for key in keywords if key in row[0].value]
    # if any keywords found, enter the keywords in column D
    # and how many keywords into column E
    if len(keywords_found):
        row[1].value = keywords_found
        row[2].value = len(keywords_found)

现在,我明白哪里我错了,因为 ws.iter_rows(..) returns 一个元组,不能修改的。我想我可以有两个 for 循环,一个用于每一行,另一个用于每一行中的列,但这个测试是真实场景的一个小例子,其中的行数为数万。

我不太确定哪种方法最好。预先感谢您提供的任何帮助。

使用ws['C'],然后使用相关单元格的offset()方法。

感谢查理 offset() 的提示。我稍微修改了代码,现在它可以正常工作了。

for row in ws.iter_rows("C{}:C{}"...)
    for cell in row:
    ....
    if len(keywords_found):
        cell.offset(0,1).value = str(keywords_found)
        cell.offset(0,2).value = str(len(keywords_found))