Home > Net >  Calling function over a Variable predefined in Python
Calling function over a Variable predefined in Python

Time:03-04

how can I link word_for_replace to the value of firstword. Can someone help me please ? Bassicaly I need to replace the value of fisrstword in test.xlsx I also need to call this function later for the value of secondword(for eg)


def replace_word():
    word_for_replace =
    i = 0
    for r in range(1, sheet.max_row   1):
        for c in range(1, sheet.max_column   1):
            s = sheet.cell(r, c).value
            if s != None and word_for_replace in s:
                sheet.cell(r, c).value = s.replace(word_for_replace, "ZZZZZZZZZZZZ")

                print("row {} col {} : {}".format(r, c, s))
                i  = 1

    data.save('C:\\Users\\ancoman\\Desktop\\testX.xlsx')
    print("{} cells updated".format(i))


def find_freq():
    for cell in range(1, 3000):
        data = sheet.cell(row=cell, column=2).value
        if data is not None:
            data=data.lower()
            data_no_pct = data.translate(str.maketrans('', '', string.punctuation))
            big_data.append(data_no_pct)
    x = " ".join(big_data)

    split_it = x.split()

    Count1 = Counter(split_it)

    most_occur1 = Count1.most_common(20)

    print(most_occur1)



find_freq()
firstword = input('Please type word from list:  ')
word_list_for_replace.append(firstword)
print('FirstWord is: '   firstword)
replace_word()

CodePudding user response:

You simply need to define word_for_replace as an argument of your function. Then you can pass any variable (here firstword) when calling the function.

It should look like this:

def replace_word(word_for_replace):
    i = 0
    for r in range(1, sheet.max_row   1):
        for c in range(1, sheet.max_column   1):
            s = sheet.cell(r, c).value
            if s != None and word_for_replace in s:
                sheet.cell(r, c).value = s.replace(word_for_replace, "ZZZZZZZZZZZZ")
[...]

find_freq()
firstword = input('Please type word from list:  ')
word_list_for_replace.append(firstword)
print('FirstWord is: '   firstword)
replace_word(firstword)
  • Related