Python在2000个字符后拆分字符串

2024-05-21 03:36:17 发布

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

我正在开发一个可以返回维基百科文章摘要的discord机器人。但有一个问题,一些摘要超过2000个字符,这超过了discord的字符限制。有没有办法将字符串拆分为多条消息

我要拆分的字符串是str(wikipedia.search(query))(整个内容都在一个嵌入块中):

embedVar = discord.Embed(title=str(query)
description=str(wikipedia.search(query)), color=0x9CAFBE)
await message.channel.send(embed=embedVar)

Tags: 字符串消息内容search文章机器人embedwikipedia
2条回答

这里有一个解决方案:

article = "5j5rtOf8jMePXn7a350fOBKVHoAJ4A2sKqUERWxyc32..." # 4000 character string i used 
chunklength = 2000
chunks = [article[i:i+chunklength ] for i in range(0, len(article), chunklength )]

print(len(chunks))

输出

2

关于如何使用它的扩展:

for chunk in chunks: 
    embedVar = discord.Embed(title="article name",
                         description=chunk ,
                         color=0x9CAFBE) 
await ctx.send(embed=embedVar)

要扩展Darina的评论,请在发布到discord之前拼接字符串

posted_string = str(wikipedia.search(query))[:2000]
embedVar = discord.Embed(title=str(query),
                         description=posted_string,
                         color=0x9CAFBE) await message.channel.send(embed=embedVar)

“字符串”是一个字符数组。当您使用[:2000]将其分配给另一个变量时,您告诉解释器将数组开头的所有字符都放在第2000个字符之前,但不包括第2000个字符

编辑: 正如Ironkey在评论中提到的,硬编码值是不可行的,因为我们不知道一篇文章有多少个字符。请尝试以下未经测试的代码:

wiki_string = str(wikipedia.search(query))
string_length = len(wiki_string)
if string_len < 2000:
    embedVar = discord.Embed(title=str(query),
                         description=wiki_string,
                         color=0x9CAFBE)
    await message.channel.send(embed=embedVar)
else:
    max_index = 2000
    index = 0
    while index < (string_length - max_index): 
        posted_string = wiki_string[index:max_index]
        embedVar = discord.Embed(title=str(query),
                         description=posted_string,
                         color=0x9CAFBE)
        await message.channel.send(embed=embedVar)
        index = index + max_index
    posted_string = wiki_string[index-max_index:]
    embedVar = discord.Embed(title=str(query),
                         description=wiki_string,
                         color=0x9CAFBE)
    await message.channel.send(embed=embedVar)

如果这不起作用,请让我知道它失败的地方。谢谢

相关问题 更多 >