Home > Blockchain >  Is there a way to put multiple for loops in a def function?
Is there a way to put multiple for loops in a def function?

Time:12-19

I've written a code using Openpyxl module that searches for multiple instances of a specific word in a column, counts how many times it appears, and then puts the total value in another cell. The code looks like this:

word = 0
for i in ws["B"]:
    if i.value == "word":
        word  = 1
ws["M2"] = word

It works but the issue is that when I need to search for multiple words I have to copy/paste this code for every word changing only the word itself and the cell I want the total value to go to.

I'm wondering if there is a way to write a function that repeats the loop taking the two variables declared somwhere else.

I've tried looking for a way to create a dictionary that holds two keys X and Y and then assiging each word to X and each column letter to Y (the column number doesn't need to change) but couldn't make it happen and I don't even know if this is the right way to go about it.

CodePudding user response:

Of course, you can define a function taking the word and the column of the output cell as arguments. For example:

def count_word(word: str, out_col: str) -> None:
    cnt = 0
    for i in ws["B"]:
        if i.value == word:
            cnt  = 1
    ws[f'{out_col}2'] = cnt

Then you can use it with a dict:

words = {
    'word1': 'M',
    'word2': 'N',
    'word3': 'O',
}

for word, out_col in words.items():
    count_word(word, out_col)
  • Related