如何在诅咒中将文本换行到下一行?

发布于 2025-01-13 09:57:04 字数 349 浏览 0 评论 0原文

我正在尝试使用curses在终端中显示文本文件,但文件的某些行大于我的终端的大小。如何将这个溢出的文本换行到下一行?

    def display(self):
        max_y, max_x = self.stdscr.getmaxyx()

        text_list = self.text.split("\n")

        for y in range(len(text_list)): 
            for x in range(len(text_list[y])):
                self.stdscr.addstr(y, x, text_list[y][x])

I am trying to display text files in the terminal using curses, but some lines of the file are larger than the size of my terminal. How can I wrap this overflowing text to the next line?

    def display(self):
        max_y, max_x = self.stdscr.getmaxyx()

        text_list = self.text.split("\n")

        for y in range(len(text_list)): 
            for x in range(len(text_list[y])):
                self.stdscr.addstr(y, x, text_list[y][x])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饭团 2025-01-20 09:57:04

我建议看看 textwrap (它是标准库的一部分)。考虑以下示例

import textwrap
text = '''This is first paragraph
This is second paragraph which is also longest
This is last paragraph'''
paras = text.splitlines()
lines = [j for i in paras for j in textwrap.wrap(i,width=25)]
print(lines)

输出

['This is first paragraph', 'This is second paragraph', 'which is also longest', 'This is last paragraph']

注意:出于说明目的,我使用 25 作为宽度。我使用嵌套理解来获取平面列表,因为在列表元素上使用 textwrap.wrap 会给出嵌套列表(list of list),您可能会选择其他方式来压平此类列表。

I suggest taking look at textwrap (it is part of standard library). Consider following example

import textwrap
text = '''This is first paragraph
This is second paragraph which is also longest
This is last paragraph'''
paras = text.splitlines()
lines = [j for i in paras for j in textwrap.wrap(i,width=25)]
print(lines)

output

['This is first paragraph', 'This is second paragraph', 'which is also longest', 'This is last paragraph']

Note: I used 25 as width for illustration purposes. I used nested comprehension to get flat list, as using textwrap.wrap on elements of list gives nested list (list of lists), you might elect other way to flatten such list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文