4

I'm trying to split up a string of characters into a list while excluding certain substrings.

For example:

>>> sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
>>> substring1 = '<s>'
>>> substring2 = '</s>'
>>> print(split_string(sentences))
['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', 
'.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd',
'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

As you can see, the string is split up into characters, except for the listed substrings. How can I do this in Python?

0

3 Answers 3

4

You could use re.findall for this. :)

import re
sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
print(re.findall(r'<\/?s>|.',sentences))

OUTPUT

['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']
Sign up to request clarification or add additional context in comments.

Comments

3

You can use re.split:

import re
s = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
result = [i for b in re.split('\<s\>|\</s\>', s) for i in ['<s>', *b, '</s>'] if b]

Output:

['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

Comments

1

Are you trying to exclude from the above output the <s> and </s> substrings?

If so:

>>> sentences = '<s>I like dogs.</s><s>It\'s Monday today</s>'
>>> substrings = ['<s>','<\s>']
>>> [character for character in split(sentences) if character not in substrings]

will give the expected output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.