Created
January 12, 2016 07:28
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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