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>

<pre><code>def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

myFile = open("file.txt", "r")
content = myFile.read()
totalValue = 0

all_colon_indexes = find(content,':')

for i in range(0,len(content)):
    if content[i]==':':
        if content[i-1]=='a':  #THIS IS WHERE YOU SPECIFY 'a' or 'b' or 'c', etc
            value=''
            index = i+1
            while True:
                if content[index].isdigit()==True:
                    value=value+content[index]
                    index=index+1
                else:
                    break
            _value = int(value)
            totalValue = totalValue + _value

print totalValue
</code></pre>

<p>result:</p>

<pre><code>20
</code></pre>

python string file python-3.x