首页 > 解决方案 > 如何让 Python 从我的 Discord 机器人的 .txt 文档中读取列表

问题描述

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 文件通过访问另一个文件中的单词并过滤我完成它的方式来获得相同的成就。请尽快告诉我!谢谢。

标签: pythonarrayslistarraylistdiscord.py

解决方案


您的代码效率低下,因为您在您的坏词列表上进行迭代,并且对于消息(for 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),一旦发现一个坏词就会停止。

你应该测试和比较。


推荐阅读