'Find specific values in a txt file and adding them up with python

I have a txt file which looks like that:

[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W 
Ampere=3 A 
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999
    
[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W 
Ampere=6 A 
Irrevelent=93 C

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers



Solution 1:[1]

Here's a quick and dirty way to do this, reading line by line, if the input file is predictable enough.

In the example I just print out the titles and the values; you can of course process them however you want.

f = open('file.dat','r')

for line in f.readlines():

    ## Catch the title of the line:
    if '[Chapter' in line:
        print(line[9:-2])

    ## catch the values of Volt, Watt, Amere parameters
    elif line[:4] in ['Volt','Watt','Ampe']:
        value = line[line.index('=')+1:line.index(' ')]
        print(value)

    ## if line is "Irrelevant", or blank, do nothing

f.close()

Solution 2:[2]

There are many ways to achieve this. Here's one:

d = dict()
V = {'Volt', 'Watt', 'Ampere'}
with open('chapter.txt', encoding='utf-8') as f:
    key = None
    for line in f:
        if line.startswith('[Chapter'):
            d[key := line.strip()] = 0
        elif key and len(t := line.split('=')) > 1 and t[0] in V:
            d[key] += float(t[1].split()[0])

for k, v in d.items():
    if v > 0:
        print(f'Total for {k} = {v}')

Output:

Total for [Chapter.Title1] = 6
Total for [Chapter.Title2] = 15

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 Elisabeth
Solution 2