簡體   English   中英

檢查文本文件中的單詞

[英]Checking word in text file

嗨,我正在為Discord創建一個反鏈接垃圾郵件bot,並試圖刪除其中包含某些關鍵字/ URL的郵件。

關鍵字列表保存在一個名為/banned_words.json的單獨文件中,我希望當消息中檢測到關鍵字時,機器人從該文件中讀取並刪除該消息。

這是我正在使用的代碼的片段, if word in word_set: ,我將在這一行代碼中苦苦掙扎if word in word_set:因此,感謝您提供有關如何定義word的示例。

def __init__(self, bot):
    self.bot = bot
    self.bannedwords = dataIO.load_json('data/spamfilter/banned_words.json')

async def banned_words(self, message):
    word = word in line.split():
    word_set = set(self.bannedwords)
    if word in word_set:
        await self.bot.delete_message(message)
        msg = await self.bot.send_message(
            message.channel,
            "{}, **Avertisement is not allowed on this server.**".format(
                message.author.mention
            )
        )
        await asyncio.sleep(6)
        await self.bot.delete_message(msg)
        return

這行是完全錯誤的:

word = word in line.split():

首先,末尾有一個多余的冒號。 其次, x in y產生一個布爾值,該布爾值表示x是否在y

您將必須遍歷消息中的所有單詞,並對每個單詞進行檢查:

word_set = set(self.bannedwords)
for word in line.split():
    if word in word_set:

這是使用內置的any功能設置的方式:

class MyCog:
    def __init__(self, bot):
        self.bot = bot
        self.bannedwords = set(dataIO.load_json('data/spamfilter/banned_words.json'))

    async def banned_words(self, message):
        words = set(message.content.split())
        word_set = self.bannedwords
        if any(word in word_set for word in words):
            await self.bot.delete_message(message)
            msg = await self.bot.send_message(
                message.channel,
                "{}, **Avertisement is not allowed on this server.**".format(
                    message.author.mention
                )
            )
            await asyncio.sleep(6)
            await self.bot.delete_message(msg)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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