OpenPyXl检查关键字,然后在单元格旁边修改以包含这些关键字和总计



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

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

然后,

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

关键字的内容和results.xlsx文件这里

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(..)中返回一个元组,无法修改。我认为我可以两个用于循环,每行一个,另一行,另一行,但此测试是现实世界场景的一个小例子,其中行的数量位于数以万计的情况下。p>我不确定哪种是最好的方法。谢谢您提前提供的任何帮助。

使用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))

相关内容

最新更新