[英]In Python, how can I read a text document line-by-line and print the number of same characters in a row at the end of each line?
I have a program which converts a simple image (black lines on white background) into 2 character ASCII art ("x" is black and "-" is white).我有一个程序可以将一个简单的图像(白色背景上的黑线)转换为 2 个字符的 ASCII 艺术(“x”是黑色,“-”是白色)。
I want to read each line and print the number or same character in a row at the end of each line.我想读取每一行并在每行末尾连续打印数字或相同字符。 Do you know how I can do this?
你知道我该怎么做吗?
for example:例如:
---x--- 3 1 3
--xxx-- 2 3 2
-xxxxx- 1 5 1
in the top row there are 3 dashes 1 'x' and 3 dashes, and so on.在顶行有 3 个破折号 1 'x' 和 3 个破折号,依此类推。 I would like these numbers to be saved to the ASCII text document.
我希望将这些数字保存到 ASCII 文本文档中。
Thank you!谢谢!
You can use itertools.groupby
:您可以使用
itertools.groupby
:
from itertools import groupby
with open("art.txt", 'r') as f:
for line in map(lambda l: l.strip(), f):
runs = [sum(1 for _ in g) for _, g in groupby(line)]
print(f"{line} {' '.join(map(str, runs))}")
# ---x--- 3 1 3
# --xxx-- 2 3 2
# -xxxxx- 1 5 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.