Reputation: 415
I would like to split a string in python and make it into a dictionary such that a key is any chunk of characters between two capital letters and the value should be the number of occurrences of these chunk in the string.
As an example: string = 'ABbACc1Dd2E'
should return this: {'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}
I have found two working solution so far (see below), but I am looking for a more general/elegant solution to this, possibly a one-line regex condition.
Thank you
Upvotes: 0
Views: 115
Reputation: 415
Thanks to usr2564301 for this suggestion:
The right regex is '[A-Z][a-z]*\d*'
import re
string = 'ABbACc1Dd2E'
print(re.findall(r'[A-Z][a-z]*\d*', string))
['A', 'Bb', 'A', 'Cc1', 'Dd2', 'E']
One can then use itertools.groupby to make an iterator that returns consecutive keys and groups from the iterable.
from itertools import groupby
all_dict = {}
for i,j in groupby(re.findall(r'[A-Z][a-z]*\d*', string)):
all_dict[i] = all_dict[i] + 1 if i in all_dict.keys() else 1
print(all_dict)
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}
Ultimately, one could use sorted()
to get this in one line with the correct counting:
print({i:len(list(j)) for i,j in groupby(sorted(re.findall(r'[A-Z][a-z]*\d*', string))) })
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}
Upvotes: 0
Reputation: 415
Solution 1
string = 'ABbACc1Dd2E'
string = ' '.join(string)
for ii in re.findall("([A-Z] [a-z])",string) + \
re.findall("([A-Z] [0-9])",string) + \
re.findall("([a-x] [0-9])",string):
new_ii = ii.replace(' ','')
string = string.replace(ii, new_ii)
string = string.split()
all_dict = {}
for elem in string:
all_dict[elem] = all_dict[elem] + 1 if elem in all_dict.keys() else 1
print(all_dict)
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}
Solution 2
string = 'ABbACc1Dd2E'
all_upper = [ (pos,char) for (pos,char) in enumerate(string) if char.isupper() ]
all_dict = {}
for (pos,char) in enumerate(string):
if (pos,char) in all_upper:
new_elem = char
else:
new_elem += char
if pos < len(string) -1 :
if string[pos+1].isupper():
all_dict[new_elem] = all_dict[new_elem] + 1 if new_elem in all_dict.keys() else 1
else:
pass
else:
all_dict[new_elem] = all_dict[new_elem] + 1 if new_elem in all_dict.keys() else 1
print(all_dict)
{'A': 2, 'Bb': 1, 'Cc1': 1, 'Dd2': 1, 'E': 1}
Upvotes: 2