通过 Python 中预定义的变量调用函数

Calling function over a Variable predefined in Python

我怎样才能link word_for_replace到firstword的值。有谁可以帮助我吗 ? Bassicaly 我需要替换 test.xlsx 中 firstword 的值 我还需要稍后调用此函数以获得 secondword 的值(例如)


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()

您只需将 word_for_replace 定义为函数的参数。 然后调用函数的时候可以传入任意变量(这里firstword

它应该是这样的:

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)