Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python中从列表中删除单词_Python 3.x - Fatal编程技术网

Python 3.x 如何在python中从列表中删除单词

Python 3.x 如何在python中从列表中删除单词,python-3.x,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.spli

到目前为止,我已经完成了我的代码,但它在使用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
输入查询
让他们哭吧,试试死吧
让他们试试
回溯(最近一次呼叫最后一次):
文件“C:\Users\Pallavi\workspace\py\src\parser.py”,第17行,在
如果(列表[j]==单词[i]):
索引器:列表索引超出范围
您出现的错误(除了我的其他注释外)是因为您在迭代列表时正在修改列表。但是您在开始时获取列表的长度,因此,在删除一些元素后,您无法访问最后的位置

我会这样做:

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)
一种更具python风格的方式,使用:


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

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

从列表中删除单词的一个更简单的方法是将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)

它应该是
words[i]
而不是
words(i)
。另外,不要调用变量
list
str
,因为它们也用于标准类。(当你有问题时,粘贴你的错误消息;它通常包含解决方案。)我已经修改了这个错误,但仍然得到了这个错误。输入查询让他们哭吧try diesd Traceback(最后一次调用):文件“C:\Users\Pallavi\workspace\py\src\parser.py”,第17行,让他们尝试如果(列表[j]==words[i]):IndexError:list index超出范围,那么实际显示错误又如何呢?或者你期望什么,得到什么?有什么想法,为什么我在数据上这样做对我不起作用?它仍然保留着以前的werewell;它应该可以工作,除非你做得不正确或者你的设置不一样。如果你仍然有这个问题,考虑一个新的问题来给出所有相关的信息。<代码>单词=设置(单词)< /代码>将删除单词的副本。如果计算频率或创建单词云,则可能不适用。
new_words = list(filter(lambda w: w not in stop_words, initial_words))
words = ['a', 'b', 'a', 'c', 'd']
words = set(words)
stopwords = ['a', 'c']
stopwords = set(stopwords)
final_list = words - stopwords
final_list = list(final_list)