如何将字符串的最后一个字输出到python中的最后一行

如何将字符串的最后一个字输出到python中的最后一行,python,python-imaging-library,Python,Python Imaging Library,我目前正在利用regex、docx和PIL从文档中提取文本,从一个关键字到另一个关键字进行读取,并将提取的字符串输出到我在代码循环中创建的图像上。我现在所有的东西都在工作,现在唯一阻碍我的是我无法在输出图像的最后一行上获得要输出的字符串的最后4个字符。以下是与此问题相关的代码: for match in find_matches(text=docText, keywords=("responsive", "detecting", "providi

我目前正在利用regex、docx和PIL从文档中提取文本,从一个关键字到另一个关键字进行读取,并将提取的字符串输出到我在代码循环中创建的图像上。我现在所有的东西都在工作,现在唯一阻碍我的是我无法在输出图像的最后一行上获得要输出的字符串的最后4个字符。以下是与此问题相关的代码:

for match in find_matches(text=docText, keywords=("responsive", "detecting", "providing")):
    match_words = match.split(" ")
    match = " ".join(match_words[:-4]) + "\n" + match_words[-4]
    W, H = 300, 300
    base = Image.new('RGB', (W, H), (255, 255, 255))
    draw = ImageDraw.Draw(base)
    font = ImageFont.load_default()

    current_h, pad = 50, 5

    for key in textwrap.wrap(match, width=50):
        line = key.encode('utf-8')
        w, h = draw.textsize(line, font=font)
        draw.text(((W - w) / 2, current_h), line, (0, 0, 0), font=font)
        current_h += h + pad
    for count, matches in enumerate(match):
        base.save(f'{match[-4:]}.png')
        bbox = ImageOps.invert(base).getbbox()
        trim = base.crop(bbox)
        patent = ImageOps.expand(trim, border=10, fill=(255, 255, 255))
        patent = ImageOps.expand(patent, border=3, fill=(0, 0, 0))
        patent.save(f'{match[-4:]}.png')

从这段代码中,我展示了两个示例输出:

我希望能够完成的任务如下图所示:

也就是说,将字符串的最后4个字符(例如:248C和249C)输出到图像的最后一行,而不附带任何其他字符。 目前,以下几行似乎对代码的结果没有任何影响,如果没有这些行,输出将保持不变:

match_words = match.split(" ")
match = " ".join(match_words[:-1]) + "\n" + match_words[-1]
非常感谢您的帮助。

x=“你好,世界”

打印(x[:-5:-1])

输出:- 德洛


字符串的最后4个字

多亏了Rob在评论中的贡献,我发现我必须用一个不同的变量创建另一个for循环,该变量存储了所有最后一行字符串,并使用该变量在下一行输出,如代码和输出所示:

for match in find_matches(text=docText, keywords=("responsive", "detecting", "providing")):
    match_words = match.split(" ")
    part = " ".join(match_words[-1:])
    match = " ".join(match_words[:-1])
    W, H = 300, 300
    base = Image.new('RGB', (W, H), (255, 255, 255))
    draw = ImageDraw.Draw(base)
    font = ImageFont.load_default()

    current_h, pad = 50, 5

    for key in textwrap.wrap(match, width=50):
        line = key.encode('utf-8')
        w, h = draw.textsize(line, font=font)
        draw.text(((W - w) / 2, current_h), line, (0, 0, 0), font=font)
        current_h += h + pad
    for obj in textwrap.wrap(part, width=50):
        partNum = obj.encode('utf-8')
        w, h = draw.textsize(partNum, font=font)
        draw.text(((W - w) / 2, current_h), obj, (0, 0, 0), font=font)

问题在于,您添加了一个换行符,然后将字符串包装在
textwrap.wrap
中。该函数用于单个段落,并再次删除换行符。最好在textwrap循环之外单独写最后一个单词。谢谢!从这里得到的。只需要再做一个for循环。