题目:打开文件 romeo.txt 并逐行阅读。 对于每一行,使用 split() 方法将该行拆分为单词列表。 该程序应该建立一个单词列表。 对于每一行的每个单词,检查该单词是否已经在列表中,如果不在列表中,则将其添加到列表中。 程序完成后, 对单词进行排序和打印。
解决:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
uu=list()
for line in fh:
line=line.rstrip()
uu=uu+line.split()
for i in range(len(uu)):
aa=uu[i]
if aa not in lst:
lst.append(aa)
lst.sort()
print(lst)
结束
附: romeo.txt的内容为:
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
执行结果:
['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']