【问题标题】:Python Split string after 2000 characters2000个字符后的Python拆分字符串
【发布时间】:2021-01-30 01:41:55
【问题描述】:

我正在开发一个可以返回维基百科文章摘要的不和谐机器人。但有一个问题,一些摘要超过 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)

【问题讨论】:

  • string[:2000] 不起作用?

标签: python string split discord wikipedia-api


【解决方案1】:

这里有一个解决方案:

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)

【讨论】:

    【解决方案2】:

    要扩展 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 在 cmets 中提到的,硬编码值是不可行的,因为我们不知道一篇文章有​​多少个字符。试试这个未经测试的代码:

    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)
    

    如果这不起作用,请告诉我失败的地方。谢谢!

    【讨论】:

    • is there a way I can split my string into multiple messages?
    • 再次拼接字符串。在这种情况下,posted_string2 = str(wikipedia.search(query))[2000:4000]。这会抓取从索引 2000 到但不包括索引 4000 的字符。
    • 如果你不知道长度怎么办;硬编码不是一个足够的解决方案
    • 无论文章大小如何,我都使用应该可以工作的代码编辑了我的答案。
    • 干得好就够了!
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多