繁体   English   中英

如何编写接收字符串消息并返回带有分页的字符串消息列表的函数

[英]How to write function that takes in a string message and returns a list of string messages with pagination

我想编写一个接受字符串消息并在需要时返回带有分页的字符串消息列表的函数。

这就是我所拥有的

import textwrap

def smart_collect():
    text = input('Please Enter a text: ')
    dedented_text = textwrap.dedent(text).strip()
    wrap_text = textwrap.wrap(dedented_text, width=212)
    max_page = len(wrap_text)

    for i in range(0, max_page):
        print(f'{wrap_text[i]} ({i+1}/{max_page})')


smart_collect()

输入文字/字串:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service line at least 1 hour before your scheduled 
appointment time.

我的输出:

As a reminder, you have an appointment with Dr. Smith tomorrow at(1/1)
3:30 pm. If you are unable to make this appointment, please call our 
3:30: command not found
customer service line at least 1 hour before your scheduled customer: 
command not found
appointment time.

预期成绩

例如,以下消息具有212个字符:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service line at least 1 hour before your scheduled 
appointment time.

消息应按以下两个块发送:

As a reminder, you have an appointment with Dr. Smith tomorrow at 
3:30 pm. If you are unable to make this appointment, please call our 
customer service  (1/2)

line at least 1 hour before your scheduled appointment time. (2/2)

您不能在此处使用textwrap.fill()来达到目的:

将单个段落包装为文本,并返回包含被包装段落的单个字符串。

相反,您需要使用textwrap.wrap()

将单个段落包装在文本(字符串)中,因此每一行最多为宽度字符长。 返回输出行列表,不带最终换行符。

由于它已经返回了列表,因此您在这里没有什么可做的了。

def smart_collect():
    text = input('Please Enter a text: ')
    dedented_text = textwrap.dedent(text).strip()
    wrap_text = textwrap.wrap(dedented_text, width=100)
    return wrap_text

print(smart_collect())

现在您有了一个width=100字符长的字符串列表,现在您可以对字符串进行任何操作。 例如,如果要打印它们,则可以执行以下操作:

for each in smart_collect():
    print(each)

现在,如果您想添加分页,则可以执行以下操作:

list_strings = smart_collect()
max_page = len(list_strings)
for i in range(0, max_page):
    print(f'{list_strings[i]} ({i+1}/{max_page})')

对于您的输入,结果(宽度为100)如下所示:

提醒一下,您明天下午3:30与Smith博士约好。 如果您无法做出(1/3)
预约后,请至少在预定时间(2/3)前1小时致电我们的客户服务热线
预约时间。 (3/3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM