Search code examples
pythonfilefor-loopif-statementreadlines

Reading and print string x times


I have an assignment where I have a text file with a word on each line which forms a string. On some lines there are a number with which amount of times I have to print the string, separated by a comma and space and finish with a period

For instance:

Darth
Maul
is
a
bad
person
3

Which should then be: Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.

So far I'm quite stuck, I'm familliar with how to read the file line by line and I guess I have put the words in a list and determine when the number comes to iterate that list a number of times.

So far I have:

TEXT = input 'sith.txt'
words = []

with open(TEXT, 'r') as f:
    line = f.readline()
    for word in line:
        if string in word //is a string not an int
            words.append(string)
        else //print words + ', '

After this I'm pretty much stuck. Anyone out there that could point me in the right direction?


Solution

  • example file: filename=text.txt

    Darth
    Maul
    is
    a
    bad
    person
    3
    Foo bar
    baz
    bla
    5
    another
    demo
    2
    

    code:

    import re
    
    with open('text.txt') as fd:
        data = fd.read()
    
    regex = re.compile(r'([^\d]+)(\d+)', re.DOTALL|re.MULTILINE)
    for text, repeat in regex.findall(data):
        repeat = int(repeat)
        text = text.strip().replace('\n', ' ')
        print(', '.join([text] * repeat))
    

    output:

    Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person
    Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla, Foo bar baz bla
    another demo, another demo