[英]How to see if any item in a list is inside a string in Python?
我正在尝试检查列表中的任何项目是否在 Python 中的某个字符串中。专门针对使用 Discord.py 的 Discord 机器人。
if list(open("file.txt")) in message.content.lower():
# do stuff
具体来说,我希望我的机器人在用户发送的消息的列表中找到某个项目后执行某项操作。 我已经对我想要它执行的操作进行了编程,但这是我遇到问题的检测。
我最初尝试做的是:
if any(list(open("file.txt"))) in message.content.lower():
# do stuff
但它给了我这个错误:
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
有人可以帮我做我想做的事吗? 我已经多次寻找该做什么的答案,但没有找到适合我需要的任何东西。
PS 我只希望它的命令被调用一次,即使消息中出现了多个项目。
你在倒着做; 如果要检查消息内容中是否存在文件的任何行,则需要:
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
该生成器表达式一次从文件中读取一行,去除换行符,并检查 rest 是否在小写消息内容中的某处,生成 stream 的True
s 和False
s。 一旦看到单个真值, any
退出并返回True
(不会浪费时间检查文件的 rest),如果它从未看到真值,则返回False
。
我很确定这是因为您试图在string中找到bool (“Any” function 返回True或False ),这是不可能的。
例如,您可以这样做,但我相信有一些更有效和更快的解决方案。
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.