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>Parse the file using regular expressions:</p>

<ul>
<li><code>\w</code> stands for a word character</li>
<li><code>\d</code> stands for a digit</li>
<li><code>+</code> specifies that you want to match one or more of the preceding match groups</li>
<li><code>?</code> specifies that you want to match zero or one of the preceding match groups (to account for a minus character)</li>
<li>parentheses specify that what is matched inside them should be extracted as a group of characters so we have two groups (one for the letter, one for the number)</li>
</ul>

<p>Then use a <code>defaultdict</code> to hold the name -> sum mapping. A <code>defaultdict</code> is like an ordinary <code>dict</code>, but when the key is missing, it creates it with a default value obtained by calling the callable you supplied when creating it. In this case this is <code>int</code> which returns <code>0</code> when called.</p>

<pre><code>import re
from collections import defaultdict

value_pattern = re.compile("(\w+):(-?\d+)")
totals = defaultdict(int)

with open("file.txt", "r") as myFile:
    for line in myFile.readlines():
        values = value_pattern.findall(line)
        for name, value in values:
            totals[name] += int(value)

        print(totals.items())
        totals.clear()
</code></pre>

<p>This gives</p>

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

<p>when run on your file.</p>

python string file python-3.x