【问题标题】:How to write a function that takes in the name of a file as the argument in Python?如何编写一个以文件名作为 Python 参数的函数?
【发布时间】:2020-07-24 04:41:08
【问题描述】:

我需要创建一个函数 return_exactly_one(file_name),它以文本文件的名称作为参数,打开文本文件,并返回一个仅包含仅出现一次的单词的列表在文本文件中。我的文件是 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)))

【问题讨论】:

    标签: python function file arguments


    【解决方案1】:

    你的函数应该接受一个字符串文件名作为参数,像这样:

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

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

    return_exactly_one("test.txt")
    

    【讨论】:

    • 谢谢你,亲爱的红宝石。它按预期工作。很高兴知道这一点。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多