从txt文件中读取单词以进行单词筛选



这是我的代码,我正试图使用它来从words.txt文件中的数组中读取单词,但目前不起作用,也不知道如何做到这一点。

@client.listen('on_message')
async def msgfilter(message, member: discord.Member = None):
wordfilter = open("filter.txt", "r")
words = set(message.content.split())
if not words.isdisjoint(wordfilter.read):
await ctx.send("No")

目前,我只是把这些单词直接放在我的main.py文件中,如果用户启用了审核模块,那么在用户无法说出的单词数组中大约有50000个单词。

这些都在我的main.py文件中,但为了避免成员规避这些限制而进行的组合使它变得更长。但它目前使文档编辑或保存/关闭文件的速度变慢。

如何从文件中的数组中读取每个单词,并检查用户消息中的单词是否包含在此文档中?

这是words.txt文档的一个示例,其中的单词在一个数组中。

wordfilter = ['badword', 'badword', 'badword', 'badword', 'badword', 'badword']
wordfilter = open("filter.txt", "r")
words = set(message.content.split())
filter_words = [w[1:-1] for w in wordfilter.read().strip().split(", ")]
if not words.isdisjoint(filter_words):
await ctx.send("No")
wordfilter.close()

假设filter.txt包含格式为'word1', 'word2', 'word3', ...的信息。

你的程序慢是正常的;50万字太多了,每次发送消息时都会重新打开文件。您可能想看看是否可以将文件内容保留在内存中。不过,我真的不明白它为什么会崩溃。

最新更新