Skip to content

Instantly share code, notes, and snippets.

@hohyon-ryu
Created January 12, 2016 07:28
Show Gist options
  • Save hohyon-ryu/b4a42706b083fb86e99e to your computer and use it in GitHub Desktop.
Save hohyon-ryu/b4a42706b083fb86e99e to your computer and use it in GitHub Desktop.
Chunk a long message into chunks of max length n with the page numbers like (1/10)
def chunk(msg, n):
words = msg.split(" ")
totalPages = 1
prevTotalPages = 0
while totalPages != prevTotalPages:
chunks = []
chunk = []
for word in words:
page = "(%d/%d)" % (len(chunks) + 1, totalPages)
if len(" ".join(chunk + [page])) > n:
raise Exception("n is too small!")
if len(" ".join(chunk + [word, page])) <= n:
chunk.append(word)
else:
if not chunk:
raise Exception("n is too small!")
chunks.append(" ".join(chunk + [page]))
chunk = [word]
if chunk:
page = "(%d/%d)" % (len(chunks) + 1, totalPages)
if len(" ".join(chunk + [page])) > n:
raise Exception("n is too small!")
chunks.append(" ".join(chunk + [page]))
prevTotalPages = totalPages
totalPages = len(chunks)
return chunks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment