【问题标题】:Read Text File and Return Words as a Sorted List读取文本文件并将单词作为排序列表返回
【发布时间】:2018-12-19 06:29:22
【问题描述】:

对于 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']

如何删除列表中的重复数据?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

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.

我认为第一个选项似乎更能说明您可能希望为这项作业学习什么。

【讨论】:

  • 我知道我在某处遗漏了一个小细节
  • @PatrickArtner 你在sorted(set(whatever))。更新。我保留了for 循环,因为lst 在他逐行阅读时正在构建。 set(words) 不会每行给出一个独立的集合,然后在下一行替换它吗?当然,你可以做一些优雅的事情来解决这个问题,但优雅通常不是很易读或没有指导意义,我试图对他现有的代码做最少的修改。毕竟作业问题。
  • 你说得对,我只读了 OP 的一半,而你的还不够好 - 你需要 sorted( {word for line in fh for word in line.rstrip().split()} )with open(...) as fh: 的东西才能一口气读完。这对于家庭作业级别的可读性不高。
【解决方案2】:

代替list,使用set来收集单词。最后转化为list并排序

fname = input("Enter file name: ")
words = set()
with open(fname) as fh:
    for line in fh:
        line = line.rstrip()
        words.update(set(line.split()))

words_list = sorted(list(words))
print(words_list)

【讨论】:

    【解决方案3】:

    一种可能是使用set,可能是这样的:

    filename = input("Enter file name: ")
    words = set()
    
    with open(filename) as f:
        for line in f:
            line = line.strip()
            if len(line) > 0:
                for w in line.split()
                    w = w.strip()
                    if len(w) > 0:
                        words.add(w)
    
    print(words)
    sorted_words = list(sorted(words))
    print(sorted_words)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2012-09-23
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      相关资源
      最近更新 更多