Python: Use specific parts of a string (that looks like a list)
<p>I have a text file (file.txt):</p>

<pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10])
(B-&gt;[e:120,g:50])
(C-&gt;[a:5,f:20])
</code></pre>

<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>

<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>

<p>Note: text file is obviously not a list, even though it looks like it.</p>

<pre><code>myFile = open("file.txt", "r")

while True:
    theline = myFile.readline()
    if "a" in theline:     #Just used 'a' here as an example.
        for char in theline:
            ...        

myFile.close()
</code></pre>

<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>

<p>Thank you.</p>

<p>First, parse the couples using a regular expression which extracts them all.</p>

<p>Then use the nice <code>itertools.groupby</code> to gather the values using keys as the <code>a,b,c...</code> letter (first item of the regex tuple).</p>

<p>Finally, create tuples with variable, sum of values as integer</p>

<pre><code>import re,itertools

with open("file.txt", "r") as myFile:

    r = re.compile("(\w+):(-?\d+)")

    for l in myFile:
        tuples = r.findall(l)
        sums = []
        for variable,values in itertools.groupby(tuples,lambda t: t[0]):
            sums.append((variable,sum(int(x[1]) for x in values)))
        print(l,sums)
</code></pre>

<p>output:</p>

<pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) [('a', 15), ('b', 50), ('c', 20)]
(B-&gt;[e:120,g:50]) [('e', 120), ('g', 50)]
(C-&gt;[a:5,f:20]) [('a', 5), ('f', 20)]
</code></pre>

<p>If you want the total sum for all lines, small changes. First accumulate all tuples in a list (source line is not important), then apply <code>groupby</code> on the sorted list (or grouping won't work properly)</p>

<pre><code>import re,itertools

with open("file.txt", "r") as myFile:

  r = re.compile("(\w+):(-?\d+)")

  tuples = []
  for l in myFile:
      tuples += r.findall(l)

  sums = []
  for variable,values in itertools.groupby(sorted(tuples),lambda t: t[0]):
      sums.append((variable,sum(int(x[1]) for x in values)))
  print(sums)
</code></pre>

<p>result:</p>

<pre><code>[('a', 20), ('b', 50), ('c', 20), ('e', 120), ('f', 20), ('g', 50)]
</code></pre>

python string file python-3.x