如何从列表中删除引用?

2024-06-01 12:53:32 发布

您现在位置:Python中文网/ 问答频道 /正文

做我的朋友。我想这样做,这样你可以添加愚蠢的报价到一个名单,然后让他们随机选择。我已经完成了这么多。在

然而,我也希望能够删除不相关的,错误的报价,等等。我想知道如何才能做到这一点。在

到目前为止,我得到的是:

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import random
import pickle
import os

Client = discord.Client()
bot_prefix = "."
bot = commands.Bot(command_prefix=bot_prefix)

@bot.event
async def on_ready():
    print("Bot Online!")
    print("Name: {}".format(bot.user.name))
    print("ID: {}".format(bot.user.id))

class Main_Commands():
    def __init__(self, bot):
     self.bot = bot

# .addquote
@bot.command(pass_context = True)
async def addquote(ctx, *answer):
    answer=" ".join(answer)
    if not os.path.isfile("quote_file.pk1"):
        quote_list = []
    else:
        with open("quote_file.pk1", "rb") as quote_file:
            quote_list = pickle.load(quote_file)
    quote_list.append(answer)
    with open("quote_file.pk1", "wb") as quote_file:
        pickle.dump(quote_list, quote_file)
    await bot.say('Quote: "{}" added!'.format(answer))

# .quote
@bot.command(pass_context = True)
async def quote(ctx):
    with open("quote_file.pk1", "rb") as quote_file:
        quote_list = pickle.load(quote_file)
    await bot.say(random.choice(quote_list))

bot.run("TOKEN")

基本上,我想添加另一个函数,.removequote(),它可以删除一个特定的引号,同时保持其他引号不变。在


Tags: answerimportasyncprefixdefbotpicklecommand
1条回答
网友
1楼 · 发布于 2024-06-01 12:53:32

删除引号与添加引号非常相似,只需替换一行。而不是.append,使用list comp过滤掉不需要的引号。其他一切都可以保持不变。在

# .removequote
@bot.command(pass_context = True)
async def removequote(ctx, *answer):
    answer=" ".join(answer)
    if not os.path.isfile("quote_file.pk1"):
        quote_list = []
    else:
        with open("quote_file.pk1", "rb") as quote_file:
            quote_list = pickle.load(quote_file)

    # This line:
    quote_list = [quote for quote in quote_list if quote != answer]

    with open("quote_file.pk1", "wb") as quote_file:
        pickle.dump(quote_list, quote_file)
    await bot.say('Quote: "{}" deleted!'.format(answer))

根据服务器pickling,您可以为每个服务器使用不同的文件名,或者为pickle使用dict(我个人认为,存储在单独的文件中更有效,因为您不必加载其他服务器的引号):

^{pr2}$

相关问题 更多 >