Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

python - Using a list against an input and seeing if it contains anything within a list

Currently trying to find if an input contains anything within a list using python. I'm building a Discord Bot with rewrite, and want it to look at a message's content, and see if anything within is found in a list. I currently have it responding to messages that are equivalent to and item in the list, but I want it to respond to a message, for example that says "Hello world", not just "Hello".

greetings = ['hi', 'hello', 'bonjour', 'hola', 'hey', 'howdy', 'sup', 'welcome', 'greetings', 'yo', 'yoo', 'suh',
'hey there', 'hey y'all', 'what's up', 'whats up', 'whatsup', 'wassup', 'sup?', 'what's shakin'', 'what's new?',
'long time no see', 'good evening', 'good afternoon']


@client.event
async def on_message(message):
    await client.process_commands(message)
    content = message.content.lower()
    if message.author == client.user:
        return
    if content in greetings:
            await message.channel.send('Hello.')
            return
question from:https://stackoverflow.com/questions/65849508/using-a-list-against-an-input-and-seeing-if-it-contains-anything-within-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're checking if a whole string is in a list, e.g:

>>> content = "hey whatever 123"
>>> greetings = ["hey", "hi"]
>>> 
>>> content in greetings
False

You should use the any function to check if the message contains any greeting

>>> content = "hey whatever 123"
>>> greetings = ["hey", "hi"]
>>> 
>>> any(greeting in content for greeting in greetings)
True

Applied to your code

@client.event
async def on_message(message):
    content = message.content.lower()

    if message.author == client.user:
        return

    if any(greeting in content for greeting in greetings):
        return await message.channel.send('Hello.')

    await client.process_commands(message)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...