[英]Beginning word counting program only produces output for the last line in python
[英]How to make last word of a string output to the last line in python
我目前正在使用正则表达式、docx 和 PIL 来从文档中提取文本,从关键字读取到关键字,并将提取的字符串 output 提取到我在代码循环中创建的图像上。 我目前一切正常,现在唯一阻碍我的是我无法在 output 图像的最后一行将字符串的最后 4 个字符转换为 output。 以下是与此问题相关的代码:
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')
从这段代码中,我展示了 2 个示例输出:
我希望能够完成的工作如下图所示:
也就是说,字符串的最后 4 个字符(例如:248C 和 249C)在图像的最后一行是 output,没有其他任何内容。 目前,以下几行似乎对代码的结果没有任何影响,没有这些行,output 保持不变:
match_words = match.split(" ")
match = " ".join(match_words[:-1]) + "\n" + match_words[-1]
任何帮助是极大的赞赏。
所以感谢评论中的 Rob,我发现我必须简单地创建另一个带有不同变量的 for 循环,该变量是存储所有最后一行字符串的变量,并将其用于下一行的 output,如图所示在代码和输出中:
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)
x="你好世界"
打印(x[:-5:-1])
output:- dlro
字符串的最后 4 个单词
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.