Home > Blockchain >  Is there a way to stop detecting part of a word in a different word?
Is there a way to stop detecting part of a word in a different word?

Time:12-02

Sorry if the title is a little confusing, I'll do my best to explain further here!

I'm setting up a Discord bot and ran into an interesting issue. Our bot is called Ed and we always call his name when wanting something from him, however, I realised that since the word need has ed in it, we can accidentally call some of his functions. I was wondering how I coud simply make it clear to only consider 'ed' by itself and nothing more.

@bot.listen()
async def on_message(positive):
    if positive.author == bot.user:
        return
    
    if 'positivity' in positive.content.lower() and 'ed' in positive.content.lower():
        await positive.channel.send(random.choice(positivity))

Afterwards, I attempted to change the code like this to only consider whether there was a space before 'Ed' but this would cause issues if his name was the first thing you typed.

@bot.listen()
async def on_message(positive):
    if positive.author == bot.user:
        return
    
    if 'positivity' in positive.content.lower() and ' ed' in positive.content.lower():
        await positive.channel.send(random.choice(positivity))

I'm new to programming and I'm sure the solution is super simple, any help would be appreciated!

CodePudding user response:

I suppose positive.content.lower() is a sentence or a paragraph.

So why don't we split it for every space with:

word_list = (positive.content.lower()   " ").split(" ")
if "ed" in word_list and "positivity" in word_list:
    await positive.channel.send(random.choice(positivity))

The added space at the end there is to ensure we have at least one space, so that we don't get a list of letters instead of a list of words.

  • Related