phthon3把一段话拆分为单词,放入一个列表里,要求单词不能重复,并且按字母表顺序排列

题目:打开文件 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']
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值