Gitzee Gitzee - 1 month ago 5
Python Question

Python: Use specific parts of a string (that looks like a list)

I have a text file (file.txt):

(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])


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

totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'


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

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()


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

Thank you.

Answer
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

result:

20