Python函数消息格式化程序

时间:2019-04-16 12:29:56

标签: 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']

预期结果: 它应该不会破坏文字

2 个答案:

答案 0 :(得分:0)

这似乎行得通:

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.']

答案 1 :(得分:0)

更新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']