Python 函数消息格式化程序



我有一个任务来开发一个函数,该函数接收字符串消息并在需要时返回带有分页的字符串消息数组。在本练习中,输入消息中的最大字符数为 160。此外,不要将单词分成音节和连字符。

我的函数不满足不将单词分解为音节的功能

def sms_format(message, size):
    sms_text = []
    if len(message) == 0:
        return sms_text
    text = list(message)
    if len(text) <= size:
        new_text = ''.join(text)
        sms_text.append(new_text)
    elif len(text) > size:
        while len(text)>size:
            texts = ''.join(text[:size])
            sms_text.append(texts)
            text = text[size:]
        sms_text.append(''.join(text))
    return(sms_text)

message = "Your task is to develop a function that takes"

print(sms_format(message, 20))

实际结果: ['Your task is to deve', 'lop a function that ', 'takes']

预期成果:它不应该打破文字

似乎工作正常:

def sms_format(message, size):
    result = []
    words = message.split()
    chunk = words.pop(0)
    for word in words:
        if len(chunk + word) >= size:
            result.append(chunk)
            chunk = word
        else:
            chunk = " ".join((chunk, word))
    result.append(chunk)
    return result
message = "Your task is to develop a function that takes long text, and splits it into chunks."
print(sms_format(message, 20))

给:

['Your task is to', 'develop a function', 'that takes long', 'text, and splits it', 'into chunks.']

更新 elif 块:

elif len(text) > size:
        current_size = size
        while len(text)>size:
            texts = ''.join(text[:current_size])
            if texts[-1] == ' ' or text[:size + 1] == ' ': 
                sms_text.append(texts)
                text = text[current_size:]
                current_size = size
            else:
                current_size = current_size - 1
Output : ['Your task is to ', 'develop a function ', 'that takes']

最新更新