Search code examples
pythontext-filesfrequency

Separate frequencies using Python and write values as many times (7895 7895 7895 7895) instead of (4*7895)


I'm a basic Python user and I have a large text data file (OUT2.txt) which has many values written as 2*150 meaning there are two 150 values (150 150) or 4*7895 meaning four 7895 values ( 7895 7895 7895 7895). I want to change all these types of values into values next to each other, meaning 7895 7895 7895 7895 instead of 4*7895.

Tried this code but get the error of:

**parts = fl.split()
AttributeError: 'list' object has no attribute 'split'**

fl = open('OUT2.txt', 'r').readlines()
parts = fl.split()
lst = []
for part in parts:
    _parts = part.split('*')
    if len(_parts) == 1:
        lst.append(_parts[0])
    else:
        times = int(_parts[0])
        for i in range(times):
            lst.append(_parts[1])
open('OUT.3.txt','w+').writelines(lst)

Any suggestions please. Thanks.

FROM THIS-EXAMPLE OF TEXT DATA FILE

2*8.17997 723.188 4*33.33 3*11.0524 380.811 149.985 5*13.9643 22.8987 76.2205 2*24.7059 64.821 

INTO THIS

8.17997 8.17997 723.188 33.33 33.33 33.3 3 33.33 11.0524 11.0524 11.0524 and so on...

Solution

  • The below should work

    with open('in.txt') as f:
        out_lines = []
        lines = [l.strip() for l in f.readlines()]
        for l in lines:
            parts = l.split()
            lst = []
            for part in parts:
                _parts = part.split('*')
                if len(_parts) == 1:
                    lst.append(_parts[0])
                else:
                    times = int(_parts[0])
                    for i in range(times):
                        lst.append(_parts[1])
            out_lines.append(' '.join(lst))
    with open('out.txt', 'w') as f1:
        for line in out_lines:
            f1.write(line + '\n')
    

    in.txt

    2*8.17997 723.188 4*33.33 3*11.0524 380.811 149.985 5*13.9643 22.8987 76.2205 2*24.7059 64.821
    10*8.17997 723.188 4*33.33 3*11.0524 380.811 149.985 5*13.9643 22.8987 76.2205 2*24.7059 64.821
    

    out.txt

    8.17997 8.17997 723.188 33.33 33.33 33.33 33.33 11.0524 11.0524 11.0524 380.811 149.985 13.9643 13.9643 13.9643 13.9643 13.9643 22.8987 76.2205 24.7059 24.7059 64.821
    8.17997 8.17997 8.17997 8.17997 8.17997 8.17997 8.17997 8.17997 8.17997 8.17997 723.188 33.33 33.33 33.33 33.33 11.0524 11.0524 11.0524 380.811 149.985 13.9643 13.9643 13.9643 13.9643 13.9643 22.8987 76.2205 24.7059 24.7059 64.821