【问题标题】: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我需要创建一个函数来获取文本正文并输出文本中所有唯一单词的列表。输出列表将包含字符串
【发布时间】:2023-03-24 08:16:01
【问题描述】:

这是我得到的。当我运行它时它不起作用。有人可以帮助指导我的代码有什么问题吗?

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

返回(唯一)

Here is my code

【问题讨论】:

  • 如果你要发布 Python 代码,你需要准确地重现你的缩进。否则读者需要猜测哪些问题是你想问的问题,以及你通过弄乱缩进引入了哪些问题。

标签: python python-3.x list python-2.7 computer-science


【解决方案1】:

Set 将保存所有唯一值。如果添加重复项,则集合将忽略它。

word_list = ['hello', 'hello', 'world', 'world']

unique = set()
for word in word_list:
    if word not in unique:
        unique.add(word)
print(unique)

【讨论】:

    【解决方案2】:

    使用 set() 返回唯一值并删除重复项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 2017-09-29
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多