1

I have a complicated string and would like to try to extract multiple substring from it.

The string consists of a set of items, separated by commas. Each item has an identifier (id-n) for a pair of words inside which is enclosed by brackets. I want to get only the word inside the bracket which has a number attached to its end (e.g. 'This-1'). The number actually indicates the position of how the words should be arrannged after extraction.

#Example of how the individual items would look like
id1(attr1, is-2) #The number 2 here indicates word 'is' should be in position 2
id2(attr2, This-1) #The number 1 here indicates word 'This' should be in position 1
id3(attr3, an-3) #The number 3 here indicates word 'an' should be in position 3
id4(attr4, example-4) #The number 4 here indicates word 'example' should be in position 4
id5(attr5, example-4) #This is a duplicate of the word 'example'

#Example of string - this is how the string with the items looks like
string = "id1(attr1, is-1), id2(attr2, This-2), id3(attr3, an-3), id4(attr4, example-4), id5(atttr5, example-4)"

#This is how the result should look after extraction
result = 'This is an example'

Is there an easier way to do this? Regex doesn't work for me.

4

3 回答 3

2

为什么不是正则表达式?这行得通。

In [44]: s = "id1(attr1, is-2), id2(attr2, This-1), id3(attr3, an-3), id4(attr4, example-4), id5(atttr5, example-4)"

In [45]: z = [(m.group(2), m.group(1)) for m in re.finditer(r'(\w+)-(\d+)\)', s)]

In [46]: [x for y, x in sorted(set(z))]
Out[46]: ['This', 'is', 'an', 'example']
于 2013-06-12T04:29:52.357 回答
2

一个简单/幼稚的方法:

>>> z = [x.split(',')[1].strip().strip(')') for x in s.split('),')]
>>> d = defaultdict(list)
>>> for i in z:
...    b = i.split('-')
...    d[b[1]].append(b[0])
...
>>> ' '.join(' '.join(d[t]) for t in sorted(d.keys(), key=int))
'is This an example example'

example您在示例字符串中有重复的位置,这就是example代码中重复的原因。

但是,您的样品也不符合您的要求 - 但此结果符合您的描述。单词根据其位置指示符排列。

现在,如果你想摆脱重复:

>>> ' '.join(e for t in sorted(d.keys(), key=int) for e in set(d[t]))
'is This an example'
于 2013-06-12T04:35:06.263 回答
1

好的,这个怎么样:

sample = "id1(attr1, is-2), id2(attr2, This-1), 
          id3(attr3, an-3), id4(attr4, example-4), id5(atttr5, example-4)"


def make_cryssie_happy(s):
    words = {} # we will use this dict later
    ll = s.split(',')[1::2]
    # we only want items like This-1, an-3, etc.

    for item in ll:
        tt = item.replace(')','').lstrip()
        (word, pos) = tt.split('-')
        words[pos] = word
        # there can only be one word at a particular position
        # using a dict with the numbers as positions keys 
        # is an alternative to using sets

    res = [words[i] for i in sorted(words)]
    # sort the keys, dicts are unsorted!
    # create a list of the values of the dict in sorted order

    return ' '.join(res)
    # return a nice string


print make_cryssie_happy(sample)
于 2013-06-12T07:01:29.153 回答