我已經從一個函式回傳純多行文本,我應該在 Telegram 或 Discord 中列印。問題是一封郵件的字符限制。文本只能用行分隔。例如
limit = 50
text = "Line1 - some text
Line2 - some text
Line3 - some text, limit here
Line4 - some text"
我需要做某事才能得到
text1 = "Line1 - some text
Line2 - some text"
text2 = "Line3 - some text, limit here
Line4 - some text"
或任何其他方式將長字串分成幾個部分,但只能按行。
這是錯誤的結果:
text1 = "Line1 - some text
Line2 - some text
Line3 - some"
text2 = "text, limit here
Line4 - some text"
uj5u.com熱心網友回復:
一個簡單的解決方案是這樣的
def send(x):
#put your sending code here
print(x)
s = "10\n1\n101\n10\n1" #example input
s= s.split("\n") # divides the string into lines
print(s)
#we want to send as many lines as possible without the total size of the sent string being over limit
limit = 3 #make this whatever you want
sending = ""
total = 0
for line in s:
if total len(line) > limit:
send(sending[:-1])
total = len(line)
sending = line "\n"
else:
total = len(line)
sending = line "\n"
#need to send the final string; there is probably a better way to do this, especially because this will break if the first if is entered on the last iteration
send(sending[:-1])
我懷疑有一種更好的方法可以在短短幾行中使用一些巧妙的拆分或正則運算式來完成此操作,但這是一種將其逐行拆分為較小訊息的粗暴方法。請注意,這將嘗試發送超過字符限制的行,并且絕對可以改進。
uj5u.com熱心網友回復:
將資料拆分到緩沖區的簡單示例
import re
limit = 50
text = "Line1 - some text\nLine2 - some text\nLine3 - some text, limit here\nLine4 - some text"
tring_array=re.split('(\n)(\r\n)',text)
message=""
for current_str in string_array:
if (len(message) len(current_str) 1) <= limit:
message =(current_str '\n')
else:
if len(message) == 0:
print "buffer to smal or empty string"
break
else:
print "Message: %sSize: %d" % (message,len(message))
message=current_str '\n'
if len(message)>0:
print "Message: %sSize: %d" % (message,len(message))
結果
Message: Line1 - some text
Line2 - some text
Size: 37
Message: Line3 - some text, limit here
Line4 - some text
Size: 48
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/356549.html
下一篇:我想反轉一個字符陣列,為什么在使用Arrays.sort(arr,Collections.reverseOrder())時會失敗?
