Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

---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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading