[英]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.我正在尝试检查列表中的任何项目是否在 Python 中的某个字符串中。专门针对使用 Discord.py 的 Discord 机器人。
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. PS 我只希望它的命令被调用一次,即使消息中出现了多个项目。
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.该生成器表达式一次从文件中读取一行,去除换行符,并检查 rest 是否在小写消息内容中的某处,生成 stream 的
True
s 和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
.一旦看到单个真值,
any
退出并返回True
(不会浪费时间检查文件的 rest),如果它从未看到真值,则返回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.我很确定这是因为您试图在string中找到bool (“Any” function 返回True或False ),这是不可能的。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.