Domanda

I have a long string that looks like:

s = 'label("id1","A") label("id1","B") label("id2", "C") label("id2","A") label("id2","D") label("id3","A")'

I would like to use regular expressions to creates lists of labels based on the id.

To be more clear, from the string s in the example I would like to end up with a list of results that looks like:

[("id1", ["A","B"]),
 ("id2", ["C","A","D"]),
 ("id3", ["A"])]

Using regular expressions I managed to fetch the ids and the elements:

import re
regex = re.compile(r'label\((\S*),(\S*)\)')
results = re.findall(regex,s)

With this code, results looks like:

[('"id1"', '"A"'),
 ('"id1"', '"B"'),
 ('"id2"', '"A"'),
 ('"id2"', '"D"'),
 ('"id3"', '"A"')]

Is there an easy way to obtain the data already grouped correctly from the regular expression?

È stato utile?

Soluzione

You can loop over the findall() results and collect them in a collections.defaultdict object. Do adjust your regular expressions to not include the quotes, and add some whitespace tolerance, though:

from collections import defaultdict
import re

regex = re.compile(r'label\("([^"]*)",\s*"([^"]*)"\)')
results = defaultdict(list)

for id_, tag in regex.findall(s):
    results[id_].append(tag)

print results.items()

You can replace list with set and append() with add() if all you want is unique values.

Demo:

>>> from collections import defaultdict
>>> import re
>>> s = 'label("id1","A") label("id1","B") label("id2", "C") label("id2","A") label("id2","D") label("id3","A")'
>>> regex = re.compile(r'label\("([^"]*)",\s*"([^"]*)"\)')
>>> results = defaultdict(list)
>>> for id_, tag in regex.findall(s):
...     results[id_].append(tag)
... 
>>> results.items()
[('id2', ['C', 'A', 'D']), ('id3', ['A']), ('id1', ['A', 'B'])]

You can sort this result too, if so desired.

Altri suggerimenti

Is postprocessing the result you get acceptable?

If so,

import re
# edited your regex to get rid of the extra quotes, and to allow for the possible space that occurs in label("id2", "C")
regex = re.compile(r'label\(\"(\S*)\",\ ?\"(\S*)\"\)')
results = re.findall(regex,s)
resultDict = {}
for id, val in results:
    if id in resultDict:
        resultDict[id].append(val)
    else:
        resultDict[id] = [val]

# if you really want a list of tuples rather than a dictionary:
resultList = resultDict.items()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top