【问题标题】:Filterings elements of a list过滤列表的元素
【发布时间】:2020-08-11 16:39:52
【问题描述】:

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

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] 测试测试
  • 测试测试测试

(对不起,不管什么原因,它都粘在一起了!)

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

奇怪的是,以单词“Currently”开头的句子被删除,“F1”、“F3”也被删除,但是像“Notice:”这样的东西被忽略了。任何帮助将不胜感激。

【问题讨论】:

    标签: python list filter


    【解决方案1】:

    这是一个解决方案,

    • 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]
    

    【讨论】:

    【解决方案2】:

    代码没有检查第一行,检查下一行,然后交替执行直到最后。我加入了一个“for _ in range()”循环,解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多