Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check first a few digit of every line in a string, if they are equal, print a part of those lines together

For example I have a string which is

textstring= """
0000 Onn ch=1 n=60 v=50   
0000 Onn ch=1 n=67 v=50
9600 Off ch=1 n=67 v=00
9600 Off ch=1 n=60 v=00
9600 Onn ch=1 n=62 v=50
9600 Onn ch=1 n=69 v=50
1920 Off ch=1 n=69 v=00
1920 Off ch=1 n=62 v=00
"""   

When the first four digit of lines are equal, for example 9600, how can I print 67/60/62/69 together? (which is from each of the four lines after n=)

I have tried something like below, but I don't think it work as expected

for i, char in enumerate(textstring):
    if char=="O" and (textstring[i+1]=="f" or textstring[i+1]=="n"):
        if textstring[i-5]==textstring[i+18] and textstring[i-4]==textstring[i+19] and textstring[i-3]==textstring[i+20] and textstring[i-2]==textstring[i+21]:
            if char=="n" and textstring[i+1]=="=":  #we look for "n=" in the text
                note=int (textstring[i+2]+textstring[i+3])  #we restore the int from string after "n=", the use it as a note
                note2=int (textstring[i+25]+textstring[i+26])
                print(note)
                print(note2)
like image 470
Kevin Avatar asked Oct 26 '22 19:10

Kevin


1 Answers

It is best to group lines with same codes in a dictionary, for example:

from collections import defaultdict
from pprint import pprint

d = defaultdict(list)
for line in textstring.splitlines():
  cells = line.split()
  if len(cells) > 1:
    line_id, *values = cells
    d[line_id].append(values)
pprint(d)

This will output:

defaultdict(<class 'list'>,
            {'0000': [['Onn', 'ch=1', 'n=60', 'v=50'],
                      ['Onn', 'ch=1', 'n=67', 'v=50']],
             '1920': [['Off', 'ch=1', 'n=69', 'v=00'],
                      ['Off', 'ch=1', 'n=62', 'v=00']],
             '9600': [['Off', 'ch=1', 'n=67', 'v=00'],
                      ['Off', 'ch=1', 'n=60', 'v=00'],
                      ['Onn', 'ch=1', 'n=62', 'v=50'],
                      ['Onn', 'ch=1', 'n=69', 'v=50']]})

You can then easily format this dictionary, such as:

for k, v in d.items():
  print(k, "/".join(e[2][2:] for e in v))

the output would be:

0000 60/67
9600 67/60/62/69
1920 69/62
like image 113
Selcuk Avatar answered Nov 15 '22 05:11

Selcuk