如何从python中的列表中删除单词

时间:2015-04-21 11:38:17

标签: python-3.x

我已经完成了我的代码,但是它与remove()无法正常工作..任何人都可以帮助我..

'''
Created on Apr 21, 2015

@author: Pallavi
'''
from pip._vendor.distlib.compat import raw_input
print ("Enter Query")
str=raw_input()  

fo = open("stopwords.txt", "r+")
str1 = fo.read();
list=str1.split("\n");
fo.close()
words=str.split(" ");
for i in range(0,len(words)):
    for j in range(0,len(list)):
        if(list[j]==words[i]):
            print(words[i])
            words.remove(words(i))

这是错误:

Enter Query
let them cry try diesd
let them try
Traceback (most recent call last):
  File "C:\Users\Pallavi\workspace\py\src\parser.py", line 17, in <module>
    if(list[j]==words[i]):
IndexError: list index out of range

3 个答案:

答案 0 :(得分:8)

您遇到的错误(除了我的其他评论之外)是因为您在迭代时修改了列表。但是你从一开始就取了列表的长度,因此,在你删除了一些元素后,你就无法访问最后的位置。

我会这样做:

words = ['a', 'b', 'a', 'c', 'd']
stopwords = ['a', 'c']
for word in list(words):  # iterating on a copy since removing will mess things up
    if word in stopwords:
        words.remove(word)

使用list comprehensions的更加pythonic方式:

new_words = [word for word in words if word not in stopwords]

答案 1 :(得分:4)

作为观察,这可能是另一种优雅的方式:

new_words = list(filter(lambda w: w not in stop_words, initial_words))

答案 2 :(得分:1)

从列表中删除单词的另一种简便方法是将2个列表转换为集合,然后对列表进行减法。

words = ['a', 'b', 'a', 'c', 'd']
words = set(words)
stopwords = ['a', 'c']
stopwords = set(stopwords)
final_list = words - stopwords
final_list = list(final_list)