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>No intention on stepping on Jean-Francois's toes :-) - I would suggest using <em>Counter</em> for count.</p>

<pre><code>import collections
with open("file.txt", "r") as myFile:

    r = re.compile("(\w+):(-?\d+)")
    res = collections.Counter()
    for l in myFile:
        for key, cnt in r.findall(l):
            res.update({key: int(cnt)})
</code></pre>

<p>result: <code>res</code> is now:</p>

<pre><code>Counter({'e': 120, 'b': 50, 'g': 50, 'c': 20, 'f': 20, 'a': 20})
</code></pre>

<p>you can access it like a dictionary: ex:</p>

<pre><code>res["a"] =&gt; 20
</code></pre>

python string file python-3.x