Python - 在 excel 中搜索相关单元格的程序无法正常工作

Python - program for searching for relevant cells in excel does not work correctly

我编写了一个代码来搜索 excel 文件中的相关单元格。但是,它并不像我希望的那样有效。 在伪代码中,这就是它应该做的:

Ask for input excel file
Ask for input textfile containing keywords to search for
Convert input textfile to list containing keywords
For each keyword in list, scan the excelfile
If the keyword is found within a cell, write it into a new excelfile
Repeat with next word

该代码有效,但在输入 excel 文件中存在一些关键字时未找到它们。我认为这可能与我遍历列表的方式有关,因为当我提供单个关键字进行搜索时,它可以正常工作。这是我的全部代码:https://pastebin.com/euZzN3T3

这是我怀疑工作不正常的部分。将文本文件拆分为列表效果很好(我认为)。

#IF TEXTFILE
elif btext == True:
    #Split each line of textfile into a list
    file = open(txtfile, 'r')
    #Keywords in list
    for line in file:          
        keywordlist = file.read().splitlines()
    nkeywords = len(keywordlist)    
    print(keywordlist)
    print(nkeywords)

    #Iterate over each string in list, look for match in .xlsx file
    for i in range(1, nkeywords):
        nfound = 0
        ws_matches.cell(row = 1, column = i).value = str.lower(keywordlist[i-1])
        for j in range(1, worksheet.max_row + 1):
            cursor = worksheet.cell(row = j, column = c)
            cellcontent = str.lower(cursor.value)
            if match(keywordlist[i-1], cellcontent) == True:
                ws_matches.cell(row = 2 + nfound, column = i).value = cellcontent
                nfound = nfound + 1     

和我的 match() 函数:

def match(keyword, content):
"""Check if the keyword is present within the cell content, return True if found, else False"""
if content.find(keyword) == -1:
    return False
else:
    return True

我是 Python 的新手,如果我的编码方式看起来像战区,我深表歉意。有人可以帮我看看我做错了什么(或者可以做得更好吗?)?感谢您抽出宝贵时间!

Splitting the textfile into a list works fine (I think).

这是你应该实际测试的东西(提示:它确实如此但不够优雅)。制作易于测试的代码的最佳方法是将功能单元隔离为单独的函数,即您可以制作一个采用文本文件名称和 returns 关键字列表的函数。然后您可以轻松地检查那段代码是否可以独立运行。从文件中读取行的更 pythonic 方式(这是你所做的,假设每行一个字)如下:

with open(filename) as f:
    keywords = f.readlines()

您的其余代码实际上可能比您预期的要好。我现在无法测试它(并且没有你的电子表格来尝试它),但如果你依赖 nfound 为你提供所有关键字的准确计数,你已经做了一个小但重大错误:它在循环内部设置为零,因此您只能得到最后一个关键字的计数。将 nfound = 0 移到循环外。

在 Python 中,遍历列表(或几乎任何东西)的方法不是递增整数,然后使用该整数索引列表中的值。而是遍历列表(或其他可迭代的)本身:

for keyword in keywordlist:
    ...

提示一下,您根本不需要 nkeywords。

希望这能让您走上正轨。以后提问的时候,能提供更多的错误信息,最好能够重现错误,会有很大的帮助。