【问题标题】:Reading words from a txt file for word filtering从 txt 文件中读取单词以进行单词过滤
【发布时间】:2021-03-17 20:55:27
【问题描述】:

这是我尝试使用的代码,以便从 words.txt 文件中的数组中读取单词,但目前无法正常工作并且无法弄清楚如何执行此操作。

@client.listen('on_message')
async def msgfilter(message, member: discord.Member = None):

    wordfilter = open("filter.txt", "r")

    words = set(message.content.split())
    if not words.isdisjoint(wordfilter.read):
        await ctx.send("No")

目前,我只是将这些词直接放在我的 main.py 文件中,如果用户启用了审核模块,那么在用户无法说出的词数组中大约有 50,000 个词。

这些都在我的 main.py 文件中,但是为了避免成员规避这些限制的组合使其更长。但它目前使文档编辑或保存/关闭文件的速度变慢。

如何从文件中的数组中读取每个单词并检查用户消息中的单词是否包含在此文档中?

这是 words.txt 文档的示例,其中单词包含在数组中。

wordfilter = ['badword', 'badword', 'badword', 'badword', 'badword', 'badword']

【问题讨论】:

    标签: python arrays list arraylist discord.py


    【解决方案1】:
    wordfilter = open("filter.txt", "r")
    
    words = set(message.content.split())
    filter_words = [w[1:-1] for w in wordfilter.read().strip().split(", ")]
    
    if not words.isdisjoint(filter_words):
        await ctx.send("No")
    
    wordfilter.close()
    

    假设您的 filter.txt 包含'word1', 'word2', 'word3', ... 格式的信息。

    你的程序很慢是正常的; 50k 字很多,每次发送消息时您都要重新打开文件。您可能想看看是否可以将文件内容保留在内存中。 不过,我真的不明白它为什么会崩溃。

    【讨论】:

    • 它们是 'word', 'word1', 'word2', 'word3' 但我仍然可以在不更改任何内容的情况下使用它?
    • @Cohen 不,你不能;但是我已经对其进行了调整,现在您可以正常使用它了
    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    相关资源
    最近更新 更多