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:测试 你在测试吗
- 测试 [消息]测试
- 测试
- 将
转换为禁止的单词
,以便快速查找设置
- 使用列表筛选从原始文本中筛选出禁止的单词
代码未选中第一行,选中下一行,然后交替执行直到结束。我加入了一个“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]