簡體   English   中英

讀取文本文件並將單詞作為排序列表返回

[英]Read Text File and Return Words as a Sorted List

對於Python 3中的分配,我需要創建一個程序來執行以下操作:

  1. 打開用戶選擇的文本文件
  2. 將文本文件中的所有單詞附加到列表中
  3. 排序列表中的單詞
  4. 打印符合期望結果的排序列表

我擁有的代碼將對列表進行排序,但不會將列表簡化到所需的結果。 文本文件是Romeo和Juliet的自白的前四行。

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

如果單詞已經在列表中,則您什么都不做,所以我認為這就是您所需要的。

您還可以將列表轉換為集合(集合只能包含其包含的每個唯一值的單個實例)。 那種笨拙的事情是,然后您需要將其轉換回列表以對其進行排序(盡管沒有其他庫為您提供排序選項,但集合本質上是未排序的),並與所需的輸出格式匹配(我假設他們需要列表輸出):

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

我認為第一種選擇似乎更能說明您可能期望從該作業中學到的知識。

代替列表,使用set收集單詞。 最后,轉換為列表並排序

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)

一種可能是使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM