如何编写一个函数,将文件名作为 Python 中的参数?

How to write a function that takes in the name of a file as the argument in Python?

我需要创建一个函数 return_exactly_one(file_name) 以文本文件的名称作为参数,打开文本文件, 和 returns 一个仅包含在文本文件中恰好出现一次的单词的列表。我的文件是 test.txt,但我对函数的参数有疑问。我不允许将 test.txt 作为参数,因为它是一个无效变量。当我调用该函数时,我应该在括号中放入什么?如何解决?谢谢。我的代码如下。

import string

def return_exactly_one(test):
    test = open("test.txt", "r")
    text = test.read()
    test.close()

    for e in string.punctuation:
        if e in text:
            text = text.replace(e, "")
            text_list = text.split()
            word_count_dict = {}
    for word in text_list:
        if word in word_count_dict:
            word_count_dict[word] +=1
        else:
            word_count_dict[word] = 1

    once_list = []
    for key, val in word_count_dict.items():
        if val == 1:
            once_list.append(key)

    return once_list

 print(__name__)
 if __name__ == "__main__":

    print("A list that only contains items that occurred exactly once in the text file is:\n{}.".format(return_exactly_one(test)))

您的函数应将字符串文件名作为参数,如下所示:

def return_exactly_one(filename):
    test = open(filename, "r")
    ...

然后你会像这样调用函数:

return_exactly_one("test.txt")

我不确定是什么阻止了您这样做。您只需将文件名存储为字符串并将该字符串传递给函数。因此,例如,您可以像这样将文件名作为输入:

file_name = input("Enter the name of the file:")

然后用文件名调用函数,如下所示:

return_exactly_one(file_name)

此外,在函数内部,您可以这样打开它:

test = open(file_name, "r")
# Notice, no quotes, it's a variable here, not a string