如何解决列表的过滤元素
我写了一段应该过滤剪贴板内容的代码,但是我无法使其工作。 它可以很好地处理第一个过滤步骤,但是第二个步骤则抛出了一些单词,但其余单词都保留了下来,我不知道为什么。
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测试 服务器测试 test1:测试测试 地图测试 注意:测试 dbPoll测试测试 登录:测试测试 test2:测试测试测试 test3:测试测试 test4:测试测试 您测试测试
- 测试测试 [MESSAGE]测试测试
- 测试测试测试
(很抱歉,由于任何原因它会粘在一起!)
(编辑:该文本应该在行下一行)
奇怪的是,以单词“当前”开头的句子也被删除,“ F1”,“ F3”也被删除,但是诸如“ Notice:”之类的东西被忽略了。任何帮助将不胜感激。
解决方法
这是一个解决方案,
- 将
forbidden_words
转换为set
以进行快速查找。
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]
,
代码使第一行保持选中状态,选中了下一行,并交替执行直到结束。我放入“ for _ in range()”循环,此问题已解决。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。