python删除重复单词,如何从python列表中删除重复的单词而不使用集合?

I have the following python code which almost works for me (I'm SO close!). I have text file from one Shakespeare's plays that I'm opening:

Original text 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"

And the result of the code I worte gives me is this:

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

So this is almost what I want: It's already in a list sorted the way I want it, but how do I remove the duplicate words? I'm trying to create a new ResultsList and append the words to it, but it gives me the above result without getting rid of the duplicate words. If I "print ResultsList" it just dumps a ton of words out. They way I have it now is close, but I want to get rid of the extra "and's", "is's", "sun's" and "the's".... I want to keep it simple and use append(), but I'm not sure how I can get it to work. I don't want to do anything crazy with the code. What simple thing am I missing from my code inorder to remove the duplicate words?

fname = raw_input("Enter file name: ")

fhand = open(fname)

NewList = list() #create new list

ResultList = list() #create new results list I want to append words to

for line in fhand:

line.rstrip() #strip white space

words = line.split() #split lines of words and make list

NewList.extend(words) #make the list from 4 lists to 1 list

for word in line.split(): #for each word in line.split()

if words not in line.split(): #if a word isn't in line.split

NewList.sort() #sort it

ResultList.append(words) #append it, but this doesn't work.

print NewList

#print ResultList (doesn't work the way I want it to)

解决方案

You did have a couple logic error with your code. I fixed them, hope it helps.

fname = "stuff.txt"

fhand = open(fname)

AllWords = list() #create new list

ResultList = list() #create new results list I want to append words to

for line in fhand:

line.rstrip() #strip white space

words = line.split() #split lines of words and make list

AllWords.extend(words) #make the list from 4 lists to 1 list

AllWords.sort() #sort list

for word in AllWords: #for each word in line.split()

if word not in ResultList: #if a word isn't in line.split

ResultList.append(word) #append it.

print(ResultList)

Tested on Python 3.4, no importing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值