在Python输出中居中多行文本

问题描述 投票:0回答:3

好吧,这似乎是一个非常基本的问题,但我在任何地方都找不到可行的答案,所以就在这里。

我有一些文字:

text = '''
Come and see the violence inherent in the system. Help! Help! I'm being 
repressed! Listen, strange women lyin' in ponds distributin' swords is no 
basis for a system of government. Supreme executive power derives from a 
mandate from the masses, not from some farcical aquatic ceremony. The Lady 
of the Lake, her arm clad in the purest shimmering samite held aloft 
Excalibur from the bosom of the water, signifying by divine providence that 
I, Arthur, was to carry Excalibur. THAT is why I am your king.'''

它不包含任何换行符或其他格式。 我想换行文本,以便在运行代码时它可以在 ipython 输出窗口中正确显示。我也希望它居中,并且比整个窗口宽度(80 个字符)短一点

如果我有一个短文本字符串(比行长度短),我可以简单地计算字符串的长度并用空格填充它以使其居中,或者使用

text.center()
属性来正确显示它。

如果我有一个只想换行的文本字符串,我可以使用:

from textwrap import fill
print(fill(text, width=50))

并将宽度设置为任意值

所以我以为我可以简单地:

from textwrap import fill
wrapped_text = (fill(text, width=50))
print(wrapped_text.center(80))

但它不起作用。一切都还算合理。

我确信我不是唯一尝试过这样做的人。有人可以帮我吗?

python python-3.x text output string-formatting
3个回答
5
投票

问题是

center
需要单行字符串,而
fill
返回多行字符串。

答案是

center
每一行,然后再将它们连接起来。

如果您查看

fill
的文档,它是:

"\n".join(wrap(text, ...))

因此,您可以跳过该简写并直接使用

wrap
。例如,您可以编写自己的函数来完全执行您想要的操作:

def center_wrap(text, cwidth=80, **kw):
    lines = textwrap.wrap(text, **kw)
    return "\n".join(line.center(cwidth) for line in lines)

print(center_wrap(text, cwidth=80, width=50))

虽然如果您只在一个地方执行此操作,但要立即打印出来,则可能更简单,甚至不用费心

join

for line in textwrap.wrap(text, width=50):
    print(line.center(80))

3
投票

wrapped_text
是一个字符串列表,因此循环遍历字符串并将它们居中。

import textwrap

text = "Come and see the violence inherent in the system. Help! Help! I'm being repressed! Listen, strange women lyin' in ponds distributin' swords is no basis for a system of government. Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony. The Lady of the Lake, her arm clad in the purest shimmering samite held aloft Excalibur from the bosom of the water, signifying by divine providence that I, Arthur, was to carry Excalibur. THAT is why I am your king."    

wrapped_text = textwrap.wrap(text)
for line in wrapped_text:
    print(line.center(80))

0
投票

要向图像添加两侧(左侧和右侧)内边距的文本以使其自动换行,您可以使用 PIL(Pillow)库按照以下步骤操作:

from PIL import Image, ImageDraw, ImageFont

# Load the image
image = Image.open("your_image.jpg")

# Define padding and text
padding = 70
text = "Your long text that needs to auto-wrap goes here."

# Create a drawing context
draw = ImageDraw.Draw(image)

# Load a font
font_size = 36  # Adjust the font size as needed
font = ImageFont.truetype("arial.ttf", font_size)

# Calculate the maximum text width based on image width minus padding
max_text_width = image.width - 2 * padding

# Function to split text into lines that fit within the given width
def wrap_text(text, font, max_width):
    lines = []
    current_line = ""
    
    for word in text.split():
        test_line = current_line + ("" if current_line == "" else " ") + word
        test_size = draw.textsize(test_line, font=font)
        
        if test_size[0] <= max_width:
            current_line = test_line
        else:
            lines.append(current_line)
            current_line = word
    
    if current_line:
        lines.append(current_line)
    
    return lines

# Wrap the text
wrapped_lines = wrap_text(text, font, max_text_width)

# Calculate the total text height
text_height = sum([draw.textsize(line, font=font)[1] for line in wrapped_lines])

# Calculate the vertical position for centering the text
text_y = (image.height - text_height) // 2

# Draw the wrapped text on the image
for line in wrapped_lines:
    text_width, text_height = draw.textsize(line, font=font)
    text_x = (image.width - text_width) // 2
    draw.text((text_x, text_y), line, font=font, fill="white")
    text_y += text_height  # Move to the next line

# Save or display the image
image.save("output_image.jpg")
image.show()

在此代码中:

  1. 使用
    Image.open()
    加载图像。
  2. 定义内边距(70 像素)和要添加的文本。
  3. 使用
    ImageDraw.Draw(image)
    创建绘图上下文。
  4. 使用
    ImageFont.truetype().
  5. 加载所需大小的字体
  6. 根据图像宽度减去最大文本宽度计算 填充。
  7. 实现一个函数
    wrap_text()
    将文本分割成几行 适合最大宽度。
  8. 计算文本的总高度和垂直位置 使文本居中。
  9. 在图像上绘制环绕的文本,使其垂直居中并居中 水平。
  10. 保存或显示生成的图像。

确保将

"your_image.jpg"
替换为图像路径,并根据需要调整
font size
font type
和其他参数。

© www.soinside.com 2019 - 2024. All rights reserved.