简体   繁体   中英

How to see if any item in a list is inside a string in Python?

I'm trying to check if any item in a list is in a certain string in Python. Specifically for a Discord bot using Discord.py.

if list(open("file.txt")) in message.content.lower():
        # do stuff

Specifically, I want my bot to do something once it finds an item in a list in a message a user has sent. I already have what I want it to do programmed, but it's the detection I'm having problems with.

What I had originally tried to do is:

if any(list(open("file.txt"))) in message.content.lower():
        # do stuff

But it gives me this error:

Traceback (most recent call last):
  File "E:\Projects\Python\gssbot\env\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\Projects\Python\gssbot\main.py", line 35, in on_message
    if any(list(open("file.txt"))) in message.content.lower():
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'in <string>' requires string as left operand, not bool

Can anybody help me with what I'm trying to do? I've looked for answers of what to do multiple times and haven't found anything that suits my need.

PS I only want its commands to be called once, even if there are multiple item occurrences in a message.

You're doing this backwards; if you want to check is any of the lines of the file exist in the message content, you want:

with open("file.txt") as f:  # Use with statement for guaranteed reliable file closing
    message_content = message.content.lower()  # Avoid repeated work, convert to lowercase up front
    if any(line.rstrip("\n") in message_content for line in f):
        # do stuff

That generator expression reads a line at a time from the file, strips off the newline, and checks if the rest is somewhere in the lowercase message content, producing a stream of True s and False s. As soon as a single truthy value is seen, any exits with a result of True (without wasting time checking the rest of the file), if it never sees a truthy value, it returns False .

I am pretty sure this is because you are trying to find a bool ("Any" function returns you True or False ) in a string , which is impossible.

You can do it like this for example, but I am sure there are some more effective and faster solutions.

OK = True
for item in list(open("file.txt"))):
    if item not in message.content.lower():
        OK = False
if OK:
    # your code

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