![](/img/trans.png)
[英]How can I make my discord bot send messages from a .txt file (python)
[英]How can I get Python to read a list from a .txt document for my Discord bot
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 文件以通过访问另一个文件中的单词并过滤我完成它的方式来获得相同的成就。 请尽快告诉我。 谢谢。
样本.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),一旦发现一个坏词就会停止。
你应该测试和比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.