Skip to main content
 首页 » 编程设计

python之如何在不使用集合的情况下从 python 列表中删除重复的单词

2025年05月04日22zengkefu

我有以下几乎适合我的 python 代码(我太接近了!)。我正在打开一部莎士比亚戏剧中的文本文件: 原始文本文件:

“但是柔和的光线透过那边的 window 打破了

是东方,朱丽叶是太阳

升起美丽的太阳,杀死嫉妒的月亮

谁已经病了,悲痛得脸色苍白"

我写的代码的结果是这样的:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', '休息', '东方', '羡慕', '公平', '悲伤', '是', '是', '是', '杀', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', '通过', '什么', '窗口', '与', '那边']

这几乎就是我想要的:它已经在按我想要的方式排序的列表中,但是如何删除重复的单词?我正在尝试创建一个新的 ResultsList 并将单词附加到它,但它给了我上面的结果而没有去掉重复的单词。如果我“打印 ResultsList”,它只会输出大量单词。他们现在的方式很接近,但我想摆脱额外的“and's”、“is's”、“sun's”和“the's”……我想保持简单并使用 append(),但是我不确定如何让它工作。我不想对代码做任何疯狂的事情。为了删除重复的单词,我的代码中缺少什么简单的东西?

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) 

请您参考如下方法:

mylist = ['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'] 
newlist = sorted(set(mylist), key=lambda x:mylist.index(x)) 
print(newlist) 
['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'] 

newlist 包含来自 mylist 的一组唯一值的列表,按 mylist 中每个项目的索引排序。