如何让Python从Discord bot的.txt文档中读取列表

2024-10-02 04:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件中,因为它是我服务器的自定义bot,我希望成员们无论如何都不能绕过过滤器。一旦我将列表复制到同一个文件python文件中,它就会崩溃,使py文档没有响应,并且保存速度慢。它在txt文件中工作得很好,但是如何让python文件通过访问另一个文件中的单词并按照我的方式进行过滤来获得同样的效果呢。请尽快让我知道!谢谢


Tags: 文件client过滤器message列表asyncondef
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))

您的代码效率很低,因为您对坏单词列表进行了迭代,并且每次迭代都会对消息进行一次迭代(对于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),一旦发现一个坏单词,这个测试就会停止

你应该测试和比较

相关问题 更多 >

    热门问题