简体   繁体   中英

Reading words from a txt file for word filtering

Here is my code I am trying to use in order to read words from an array in my words.txt file, but currently does not work and can't figure out how to do this.

@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")

Currently, I am just putting these words straight in my main.py file and have approximately 50,000 words within an array of words users cannot say, if they have the moderation module enabled.

These are all within my main.py file but the combinations in order to avoid members from circumventing these restrictions make it even longer. But it currently makes the document slow to edit or save/close the file.

How would it be possible to read each word from the array within the file and check if the word in the users message was included in this document?

This is an example of the words.txt document with the words within an array.

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()

Assuming your filter.txt contains information in the format 'word1', 'word2', 'word3', ... .

It's normal your program is slow; 50k words is a lot, and you're re-opening the file everytime a message is sent. You may want to see if it's possible to keep the file contents in memory instead. I can't really see why it would crash, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM