【发布时间】:2020-11-08 23:29:06
【问题描述】:
我有一个文本文件:
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)
【问题讨论】:
-
line.split()将被您可能删除的空格分隔。 -
那我应该怎么把它分成单词呢?
-
为什么“in”在“lives”之前?
-
字母顺序 ig.
-
* 'He' 将出现在 'I' 之前。
标签: python python-3.x string list file