python - 如何让 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 文件通过访问另一个文件中的单词并过滤我完成它的方式来获得相同的成就。请尽快告诉我!谢谢。
解决方案
您的代码效率低下,因为您在您的坏词列表上进行迭代,并且对于消息(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),一旦发现一个坏词就会停止。
你应该测试和比较。
推荐阅读
- excel - 如果日期重复但数据是唯一的,如何匹配日期然后将相应数据从一个电子表格复制到另一个电子表格?
- python - 返回满足熊猫数据框中条件的数据框位置的第一个值的位置
- sql - 需要帮助加入 2 个表并使用 BigQuery SQL 以独特的方式汇总它们
- reporting-services - 第一个新手问题:SSRS Tablix 可见性参数
- python - Knn 预测在 y_test 上达到 100%
- python - 无法拆分字符串
- python - 删除 CSV 文件中的方括号
- python - 是否可以结合热键和鼠标单击来选择菜单项?
- c# - 从组合框中获取价值?
- sungridengine - Grid Engine 队列优先级设置