我需要制作一个函数,它接受一段文本并输出文本中所有唯一单词的列表。输出列表将包含字符串
I need to make a function that takes a body of text and outputs a list of all unique words in the text. The output list will contain strings
这是我得到的。当我 运行 它时它不工作。有人可以帮助指导我的代码有什么问题吗?
def unique_words(text : str) ->list:
text = open(text, 'r')
text_contents = text.read()
text.close()
word_list = text_contents.split()
word = open(str, 'w')
unique = []
for word in word_list:
if word not in word_list:
file.append(str(word) + "\n")
unique.sort()
return(唯一)
Here is my code
使用 set() return 唯一值并删除重复值
Set 将包含所有唯一值。如果您添加重复项,则集合将忽略它。
word_list = ['hello', 'hello', 'world', 'world']
unique = set()
for word in word_list:
if word not in unique:
unique.add(word)
print(unique)
这是我得到的。当我 运行 它时它不工作。有人可以帮助指导我的代码有什么问题吗?
def unique_words(text : str) ->list:
text = open(text, 'r')
text_contents = text.read()
text.close()
word_list = text_contents.split()
word = open(str, 'w')
unique = []
for word in word_list:
if word not in word_list:
file.append(str(word) + "\n")
unique.sort()
return(唯一)
Here is my code
使用 set() return 唯一值并删除重复值
Set 将包含所有唯一值。如果您添加重复项,则集合将忽略它。
word_list = ['hello', 'hello', 'world', 'world']
unique = set()
for word in word_list:
if word not in unique:
unique.add(word)
print(unique)