如何解决2000个字符后的Python拆分字符串
我正在开发一个不和谐的机器人,该机器人可以返回Wikipedia文章的摘要。但是存在一个问题,某些摘要的长度超过2000个字符,超过了不和谐字符的限制。有什么办法可以将我的字符串拆分为多个消息?
我要拆分的字符串是str(wikipedia.search(query))
(整个内容都在一个嵌入块中):
embedVar = discord.Embed(title=str(query)
description=str(wikipedia.search(query)),color=0x9CAFBE)
await message.channel.send(embed=embedVar)
解决方法
这是一个解决方案:
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的评论,请在将字符串发布到不一致之前将其拼接。
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),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),color=0x9CAFBE)
await message.channel.send(embed=embedVar)
如果这不起作用,请让我知道失败的地方。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。