'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).

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. I would like these numbers to be saved to the ASCII text document.

Thank you!



Solution 1:[1]

You can use 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1