gpt4 book ai didi

python - 读取文本文件并将单词作为排序列表返回

转载 作者:太空宇宙 更新时间:2023-11-04 09:35:45 25 4
gpt4 key购买 nike

对于 Python 3 中的作业,我需要创建一个程序来执行以下操作:

  1. 打开用户选择的文本文件
  2. 将文本文件中的所有单词附加到列表中
  3. 对列表中的单词进行排序
  4. 打印与所需结果匹配的排序列表

我的代码将对列表进行排序,但不会将列表中的重复项删除到所需的结果。该文本文件是罗密欧与朱丽叶独白的前四行。

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
lst.append(word)
lst.sort()
print(lst)

期望的结果是:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

但是在我的代码中,我得到了重复的单词:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']

我怎样才能对列表进行重复数据删除?

最佳答案

有几种方法可以做到这一点。您可以检查单词是否已经在列表中,并且仅当单词不在列表中时才追加:

for word in words:
if word not in lst:
lst.append(word)
lst.sort()

如果单词已经在列表中,则无需执行任何操作,所以我认为这就是您所需要的。

您还可以将列表转换为集合(集合中包含的每个唯一值只能有一个实例)。这种笨拙的事情是你需要将它转换回列表以对其进行排序(集合本质上是未排序的,尽管有其他库为你提供排序选项),并匹配所需的输出格式(我假设他们需要一个 list 输出):

for word in words:
lst.append(word)
lst = sorted(set(lst)) # convert to set and sort in one line. Returns a list.

我假设第一个选项似乎更能说明您可能希望从这项作业中学到什么。

关于python - 读取文本文件并将单词作为排序列表返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53841745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com