Merging consecutive elements recursively in a list of strings in Python

Viewed 411

I have list of strings which need to be transformed into a smaller list of strings, depending whether two consecutive elements belong to the same phrase. This happens, at the moment, if the last character of the i-th string is lower and the first character of the i+1-th string is also lower, but more complex conditions should be checked in the future.

For example this very profound text:

['I am a boy',
'and like to play'
'My friends also'
'like to play'
'Cats and dogs are '
'nice pets, and'
'we like to play with them'
]

should become:

['I am a boy and like to play', 
 'My friends also like to play',
 'Cats and dogs are nice pets, and we like to play with them'
]

My python solution

3 Answers

I think the data you have posted is comma seperated. If it is pfb a simple loop solution.

data=['I am a boy',
'and like to play',
'My friends also',
'like to play',
'Cats and dogs are ',
'nice pets, and',
'we like to play with them'
]

required_list=[]

for j,i in enumerate(data):
    print(i,j)
    if j==0:
        req=i
    else:
        if i[0].isupper():
            required_list.append(req)
            req=i
        else:
            req=req+" "+i
required_list.append(req)


print(required_list)    

Since you want to do it recursively, you can try something like this:

def join_text(text, new_text):
    if not text:
        return
    if not new_text:
        new_text.append(text.pop(0))
        return join_text(text, new_text)
    phrase = text.pop(0)
    if phrase[0].islower():  # you can add more complicated logic here
        new_text[-1] += ' ' + phrase
    else:
        new_text.append(phrase)
    return join_text(text, new_text)


phrases = [
    'I am a boy',
    'and like to play',
    'My friends also',
    'like to play',
    'Cats and dogs are ',
    'nice pets, and',
    'we like to play with them'
]


joined_phrases = []
join_text(phrases, joined_phrases)
print(joined_phrases)

My solution has some problems with witespaces, but I hope you got the idea. Hope it helps!

Here is your code check it

data = ['I am a boy',
'and like to play'
'My friends also'
'like to play'
'Cats and dogs are '
'nice pets, and'
'we like to play with them'
]

joined_string = ",".join(data).replace(',',' ')

import re
values = re.findall('[A-Z][^A-Z]*', joined_string)
print(values)
Related