如何从单词文件的几行中拆分所有单词? (蟒蛇)

时间:2020-07-19 18:26:35

标签: python python-3.x string list file

我有一个文本文件:

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

说明:打开文件并逐行读取。对于每一行,使用split()方法将该行拆分为单词列表。该程序应建立单词列表。对于每一行中的每个单词,请检查该单词是否已在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对结果单词进行排序和打印。

所需的输出:

['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']

我被困在这里:

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

0 个答案:

没有答案
相关问题