簡體   English   中英

如何查看列表中的任何項目是否在 Python 中的字符串內?

[英]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 返回TrueFalse ),這是不可能的。

例如,您可以這樣做,但我相信有一些更有效和更快的解決方案。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM