【发布时间】: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