【问题标题】:How can I get Python to read a list from a .txt document for my Discord bot如何让 Python 从我的 Discord 机器人的 .txt 文档中读取列表
【发布时间】:2026-02-21 23:00:02
【问题描述】:
wordfilter = ["badword", "badword", "badword", "badword", "badword", "badword", "badword"]```

@client.listen('on_message')
async def msgfilter(message, member: discord.Member = None):
    global messageserver
    messageserver += 1

    for word in wordfilter:
        if message.content.count(word) > 0:
            await message.channel.purge(limit=1)

是我的代码,但我最近更新了过滤器,以匹配我的 Discord 机器人在每种语言中对词语的贬义使用。它在这样的列表中有超过 10000 行:

wordfilter = ["badword", "badword", "badword", "badword", "badword", "badword", "badword"]

但对于来自 105 多种语言的数千或单词。我试图将它放入我的主 python 文件中,因为它是我的服务器的自定义机器人,我希望成员无论如何都不能绕过过滤器。一旦我将列表复制到同一个文件 python 文件中,它就会崩溃并使 py 文档无响应并且保存速度很慢。它在 txt 文件中运行良好,但我怎样才能让 python 文件通过访问另一个文件中的单词并过滤我完成它的方式来获得相同的成就。请尽快告诉我!谢谢。

【问题讨论】:

    标签: python arrays list arraylist discord.py


    【解决方案1】:

    您的代码效率低下,因为您在坏词列表上进行迭代,并且每次迭代都在消息上再次进行(对于count),这使其成为 O(单词列表长度 * 消息长度)。

    你应该使用集合:一组你的坏词

    wordfilter = {"badword", "badword", "badword", "badword", "badword", "badword", "badword"}
    

    还有你留言中的一组词:

    words = set(message.content.split())
    

    测试消息是否包含坏词然后就是:

    if not words.isdisjoint(wordfilter):
        # there is a badword in your message
    

    这样会更有效率。

    另一个选项是测试消息的任何单词是否是集合的一部分,使用:

    words = message.content.split()
    if any(word in wordfilter for word in words):
        # there is a badword in your message
    

    测试一个项目是否在一个集合中只需 O(1),一旦发现一个坏词就会停止。

    你应该测试和比较。

    【讨论】:

      【解决方案2】:

      Sample.txt

      badword1
      badword2
      badword3
      ...
      badwordn
      

      Python 代码:

      with open("Sample.txt","r") as f:
          bad_words=f.readlines()
      print("length of all bad words are ",len(bad_words))
      

      【讨论】:

      • 我可以拥有我已经拥有的列表的txt文档吗?而不是为每个单词创建行?
      • @Cohen 是的,只需使用 python 在 .txt 文件中写入列表的元素
      最近更新 更多