python - 如何限制一次输出的字符数,以便图像到 ASCII 转换器输出不一致,每条消息限制为 2000 个字符
问题描述
我有一个与 discord bot 一起工作的图像到 ASCII 转换器,因此人们可以将图像发送给它,它会下载图像并将其转换为 ASCII 并将其发送回给他们,但是由于 Discord 将每个消息限制为 2000 个字符,因此它经常会卡住制作图像大小合理。
我使用本教程来转换图像,我相信这行代码:
asciiImage = "\n".join(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))
是我需要修复的,我相信它将图像的每一行连接到基于 newWidth 变量的换行符,当你给它图像时输入它。我如何将它限制为仅添加行,直到下一行超过 2000,输出(或将其添加到列表中)然后重复直到完成图像?
抱歉,如果这有点令人困惑。
解决方案
您可以在 for 循环中对其进行迭代并跟踪字符串的当前大小。如果添加下一行会使它太大,请发送它,重置字符串并继续。
之后,如有必要,发送字符串的最后一部分(不会在 for 循环中自动发送)。
注意:下面的这个例子假设你有一个channel
发送消息,用ctx
oruser
或任何你的意图替换它。Channel
只是为了这个例子。
# Entire ascii image as a list of lines (not joined into one string)
asciiImage = list(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))
# String to send
send_str = ""
for line in asciiImage:
# Adding this line would make it too big
# 1998 = 2000 - 2, 2 characters for the newline (\n) that would be added
if len(send_str) + len(line) > 1998:
# Send the current part
await channel.send(send_str)
# Reset the string
send_str = ""
# Add this line to the string
send_str += line + "\n"
# Send the remaining part
if send_str:
await channel.send(send_str)
推荐阅读
- r - 如何在 R 中拆分变量?
- python - Django import export 当我们在导入外键时有数据名称但没有 id
- go - 如何在循环中使用指针更改切片元素
- c++ - std::distance "没有找到匹配的重载函数"
- python - 如何在不使用 if 语句进行打印的情况下输出带小数点的值
- ios - iOS 如何调试由于超过 60 秒超过 80% cpu 的限制而终止的应用程序
- javascript - 如何使用 Interval 函数增加 noUiSlider 值?
- go - GO 新手,在条件内分配错误
- python - Python win32com 演示outlookaddin.py 控制按钮标题不起作用
- swift - SwiftUI 有没有办法改变 tabItem 的大小