Separating a string of words into characters following certain conditions

2324 views python

I have a string of words and I want to separate them into individual characters. However, if a group of characters is part of what I've called "special consonant pairs", they need to remain together.

These are some of my "special consonant pairs":

consonant_pairs = ["ng", "ld", "dr", "bl", "nd", "th" ...]

This is one of the sample strings I want to separate into characters:

sentence_1 = "We were drinking beer outside and we could hear the wind blowing"

And this would be my desired output (I have already deleted spaces and punctuation):

sentence_1_char = ['w', 'e', 'w', 'e', 'r', 'e', 'dr', 'i', 'n', 'k', 'i', 'ng', 'b', 'e', 'e', 'r', 'o', 'u', 't', 's', 'i', 'd', 'e', 'a', 'n', 'd', 'w', 'e', 'c', 'o', 'u', 'ld', 'h', 'e', 'a', 'r', 'th', 'e', 'w', 'i', 'nd', 'bl', 'o', 'w', 'i', 'ng']

I thought of using list(), though I don't know how to go about the consonant pairs. Could anyone help me?

answered question

are they always only 2?

@teclnol there are a couple cases when there are 3 consonants together. I'm sorry I didn't include any of them in my examples. My bad

1 Answer


A quick (not necessarily performant) answer:

import re
re.split('|'.join(consonant_pairs), sentence)

posted this

Have an answer?


Please login first before posting an answer.