Python 过滤列表中的元素

Python 过滤列表中的元素,python,list,filter,Python,List,Filter,我写了一段代码,用来过滤剪贴板上的内容,但我不能让它工作。 它很好地处理了第一个过滤步骤,但是第二个步骤抛出了一些单词,但保留了其余的单词,我不知道为什么 import pyperclip clipboard_content = pyperclip.paste() separated_sentences = clipboard_content.split('\r\n') filtered_sentences = list() for sentence in separated_sentenc

我写了一段代码,用来过滤剪贴板上的内容,但我不能让它工作。 它很好地处理了第一个过滤步骤,但是第二个步骤抛出了一些单词,但保留了其余的单词,我不知道为什么

import pyperclip

clipboard_content = pyperclip.paste()
separated_sentences = clipboard_content.split('\r\n')
filtered_sentences = list()

for sentence in separated_sentences:
    chopped_sentence = list(sentence)

    if chopped_sentence[0] == "[" or chopped_sentence[0] == "*":
        chopped_sentence.clear()
    else:
        filtered_sentences.append("".join(chopped_sentence))

forbidden_words = ["Map", "Currently", "Server", "Welcome", "F1", "F2", "F3", "dbPoll", "login:", "You", "Notice:"]

for sentence in filtered_sentences:
    index = filtered_sentences.index(sentence)
    words = filtered_sentences[index].split()

    for forbidden_word in forbidden_words:
        if words[0] == forbidden_word:
            filtered_sentences.pop(index)

for sentence in filtered_sentences:
    print(sentence)
下面是一些要复制的示例文本:

  • 连接! 目前 服务器测试 F1试验 F2试验 F3试验 服务器测试 测试1:测试 地图测试 注意:考试 dbPoll测试 登录:测试 测试2:测试 测试3:测试 测试4:测试 你在测试吗
  • 测试 [消息]测试
  • 测试
(对不起,不管什么原因,它都粘在一起了!)

(编辑:文本应该在第行下)

奇怪的是,以“current”开头的句子被删除,“F1”,“F3”也被删除了,但是像“Notice:”这样的东西被忽略了。非常感谢您的帮助。

这里有一个解决方案

  • 禁止的单词
    转换为
    设置
    ,以便快速查找
  • 使用列表筛选从原始文本中筛选出禁止的单词

代码未选中第一行,选中下一行,然后交替执行直到结束。我加入了一个“for u-in range()”循环,解决了这个问题

forbidden_words = set(["Map", "Currently", "Server", "Welcome", "F1", "F2", 
                       "F3", "dbPoll", "login:", "You", "Notice:"])
text = """Connected! Currently Server test test F1..."""

[x for x in text.split() if x not in forbidden_words]