Combining selected rows into a list of rows

The problem is as follows. I have a list of strings

lst1=['puffing','his','first','cigarette','in', 'weeks', 'in', 'weeks']

and I would like to get a string

lst2=['puffing','his','first','cigarette','in weeks', 'in weeks']

that is, to combine any occurrence of a subword ['in', 'weeks']for reasons that are irrelevant here, where find_sub_list1taken from here (and included in the code below):

npis = [['in', 'weeks'], ['in', 'ages']]

# given a list a candidate sublist, return the index of the first and last
# element of the sublist within the list
def find_sub_list1(sl,l):
    results=[]
    sll=len(sl)
    for ind in (i for i,e in enumerate(l) if e==sl[0]):
        if l[ind:ind+sll]==sl:
        results.append((ind,ind+sll-1))

    return results

def concatenator(sent, npis):
    indices = []
    for npi in npis:
        indices_temp = find_sub_list1(npi, sent)
        if indices_temp != []:
            indices.extend(indices_temp)
    sorted(indices, key=lambda x: x[0])

    for (a,b) in indices:
        diff = b - a
        sent[a:b+1] = [" ".join(sent[a:b+1])]
        del indices[0]
        indices = [(a - diff, b - diff) for (a,b) in indices]

    return sent 

instead of the desired, lst2this encoder returns:

concatenator(lst1,['in', 'weeks'])
>>['puffing','his','first','cigarette','in weeks', 'in', 'weeks']

therefore, it combines only the first occurrence. Any ideas on where the code doesn't work?

+6
source share
2 answers

since the desired subsequence 'in' 'weeks'and possibly'in''ages'

One possible solution could be (the loop is not very elegant):

  • , 'in'.

  • , 'in' , .. , , .

  • , IndexError, , .

:

index_in = [i for i, _ in enumerate(lst1) if _ == 'in']

lst2 = []; n = 0

while True:
    try:
         if n in index_in and lst1[n+1] in ['weeks', 'ages']:
             lst2.append(lst1[n] + lst1[n+1])
             n += 1
         else:
             lst2.append(lst1[n])
         n += 1
     except IndexError:
         break

- .

  • , , in<space>weeks. lookahead lookbehind

:

import re

c = re.compile(r'(?<!in) (?!weeks)')

lst2 = c.split(' '.join(lst1))
+2

, ( )

import re
list1_str = ','.join(lst1)
npis_concat = [','.join(x) for x in npis]
for item in npis_concat:
    list1_str = re.sub(r'\b'+item+r'\b',item.replace(',', ' '),list1_str)
lst1 = list1_str.split(',')

, , , , ,

r'\b' , , , / npis

0

Source: https://habr.com/ru/post/1016921/


All Articles