在Python中,如何逐行读取文本文档并在每行末尾打印一行中相同字符的个数?

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?

我有一个程序可以将一个简单的图像(白底黑线)转换为 2 个字符的 ASCII 艺术(“x”是黑色,“-”是白色)。

我想阅读每一行并在每一行的末尾连续打印数字或相同的字符。你知道我该怎么做吗?

例如:

---x---  3 1 3
--xxx--  2 3 2
-xxxxx-  1 5 1

顶行有 3 个破折号 1 'x' 和 3 个破折号,依此类推。 我希望将这些数字保存到 ASCII 文本文件中。

谢谢!

您可以使用 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