python re.split(): how to save some of the delimiters (instead of all the delimiter by using bracket)









up vote
2
down vote

favorite












For the sentences:



"I am very hungry, so mum brings me a cake!


I want it split by delimiters, and I want all the delimiters except space to be saved as well. So the expected output is :



"I" "am" "very" "hungry" "," "so", "mum" "brings" "me" "a" "cake" "!" "n"


What I am currently doing is re.split(r'([!:''".,(s+)n])', text), which split the whole sentences but also saved a lot of space characters which I don't want. I've also tried the regular expression s|([!:''".,(s+)n]) , which gives me a lot of None somehow.










share|improve this question



















  • 1




    Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
    – timgeb
    Nov 10 at 12:03














up vote
2
down vote

favorite












For the sentences:



"I am very hungry, so mum brings me a cake!


I want it split by delimiters, and I want all the delimiters except space to be saved as well. So the expected output is :



"I" "am" "very" "hungry" "," "so", "mum" "brings" "me" "a" "cake" "!" "n"


What I am currently doing is re.split(r'([!:''".,(s+)n])', text), which split the whole sentences but also saved a lot of space characters which I don't want. I've also tried the regular expression s|([!:''".,(s+)n]) , which gives me a lot of None somehow.










share|improve this question



















  • 1




    Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
    – timgeb
    Nov 10 at 12:03












up vote
2
down vote

favorite









up vote
2
down vote

favorite











For the sentences:



"I am very hungry, so mum brings me a cake!


I want it split by delimiters, and I want all the delimiters except space to be saved as well. So the expected output is :



"I" "am" "very" "hungry" "," "so", "mum" "brings" "me" "a" "cake" "!" "n"


What I am currently doing is re.split(r'([!:''".,(s+)n])', text), which split the whole sentences but also saved a lot of space characters which I don't want. I've also tried the regular expression s|([!:''".,(s+)n]) , which gives me a lot of None somehow.










share|improve this question















For the sentences:



"I am very hungry, so mum brings me a cake!


I want it split by delimiters, and I want all the delimiters except space to be saved as well. So the expected output is :



"I" "am" "very" "hungry" "," "so", "mum" "brings" "me" "a" "cake" "!" "n"


What I am currently doing is re.split(r'([!:''".,(s+)n])', text), which split the whole sentences but also saved a lot of space characters which I don't want. I've also tried the regular expression s|([!:''".,(s+)n]) , which gives me a lot of None somehow.







python split






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 12:26









lgwilliams

517317




517317










asked Nov 10 at 11:53









SoManyProblems

1838




1838







  • 1




    Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
    – timgeb
    Nov 10 at 12:03












  • 1




    Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
    – timgeb
    Nov 10 at 12:03







1




1




Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
– timgeb
Nov 10 at 12:03




Almost(?) a duplicate of In Python, how do I split a string and keep the separators?.
– timgeb
Nov 10 at 12:03












3 Answers
3






active

oldest

votes

















up vote
1
down vote



accepted










search or findall might be more appropriate here than split:



import re

s = "I am very hungry, so mum brings me a !#$#@ cake!"

print(re.findall(r'[^ws]+|w+', s))

# ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', '!#$#@', 'cake', '!']


The pattern [^ws]+|w+ means: a sequence of symbols which are neither alphanumeric nor whitespace OR a sequence of alphanumerics (that is, a word)






share|improve this answer






















  • could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
    – SoManyProblems
    Nov 10 at 14:09










  • @SoManyProblems: added an explanation
    – georg
    Nov 10 at 17:58

















up vote
1
down vote













That is because your regular expression contains a capture group. Because of that capture group, it will also include the matches in the result. But this is likely what you want.



The only challenge is to filter out the Nones (and other values with truthiness False) in case there is no match, we can do this with:



def tokenize(text):
return filter(None, re.split(r'[ ]+|([!:''".,sn])', text))


For your given sample text, this produces:



>>> list(tokenize("I am very hungry, so mum brings me a cake!n"))
['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





share|improve this answer




















  • why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
    – SoManyProblems
    Nov 10 at 14:01










  • @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
    – Willem Van Onsem
    Nov 10 at 14:02










  • thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
    – SoManyProblems
    Nov 10 at 14:42










  • @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
    – Willem Van Onsem
    Nov 10 at 14:43

















up vote
1
down vote













One approach is to surround the special characters (,!.n) with space and then split on space:



import re


def tokenize(t, pattern="([,!.n])"):
return [e for e in re.sub(pattern, r" 1 ", t).split(' ') if e]


s = "I am very hungry, so mum brings me a cake!n"

print(tokenize(s))


Output



['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238662%2fpython-re-split-how-to-save-some-of-the-delimiters-instead-of-all-the-delimi%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    search or findall might be more appropriate here than split:



    import re

    s = "I am very hungry, so mum brings me a !#$#@ cake!"

    print(re.findall(r'[^ws]+|w+', s))

    # ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', '!#$#@', 'cake', '!']


    The pattern [^ws]+|w+ means: a sequence of symbols which are neither alphanumeric nor whitespace OR a sequence of alphanumerics (that is, a word)






    share|improve this answer






















    • could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
      – SoManyProblems
      Nov 10 at 14:09










    • @SoManyProblems: added an explanation
      – georg
      Nov 10 at 17:58














    up vote
    1
    down vote



    accepted










    search or findall might be more appropriate here than split:



    import re

    s = "I am very hungry, so mum brings me a !#$#@ cake!"

    print(re.findall(r'[^ws]+|w+', s))

    # ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', '!#$#@', 'cake', '!']


    The pattern [^ws]+|w+ means: a sequence of symbols which are neither alphanumeric nor whitespace OR a sequence of alphanumerics (that is, a word)






    share|improve this answer






















    • could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
      – SoManyProblems
      Nov 10 at 14:09










    • @SoManyProblems: added an explanation
      – georg
      Nov 10 at 17:58












    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    search or findall might be more appropriate here than split:



    import re

    s = "I am very hungry, so mum brings me a !#$#@ cake!"

    print(re.findall(r'[^ws]+|w+', s))

    # ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', '!#$#@', 'cake', '!']


    The pattern [^ws]+|w+ means: a sequence of symbols which are neither alphanumeric nor whitespace OR a sequence of alphanumerics (that is, a word)






    share|improve this answer














    search or findall might be more appropriate here than split:



    import re

    s = "I am very hungry, so mum brings me a !#$#@ cake!"

    print(re.findall(r'[^ws]+|w+', s))

    # ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', '!#$#@', 'cake', '!']


    The pattern [^ws]+|w+ means: a sequence of symbols which are neither alphanumeric nor whitespace OR a sequence of alphanumerics (that is, a word)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 10 at 17:58

























    answered Nov 10 at 12:06









    georg

    145k34193290




    145k34193290











    • could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
      – SoManyProblems
      Nov 10 at 14:09










    • @SoManyProblems: added an explanation
      – georg
      Nov 10 at 17:58
















    • could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
      – SoManyProblems
      Nov 10 at 14:09










    • @SoManyProblems: added an explanation
      – georg
      Nov 10 at 17:58















    could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
    – SoManyProblems
    Nov 10 at 14:09




    could you explain a little bit how the pattern is constructed this way ? why [^ws]+ gives all the words but not words with space character (as s suggested)? Also why you put |w+ pattern there ?
    – SoManyProblems
    Nov 10 at 14:09












    @SoManyProblems: added an explanation
    – georg
    Nov 10 at 17:58




    @SoManyProblems: added an explanation
    – georg
    Nov 10 at 17:58












    up vote
    1
    down vote













    That is because your regular expression contains a capture group. Because of that capture group, it will also include the matches in the result. But this is likely what you want.



    The only challenge is to filter out the Nones (and other values with truthiness False) in case there is no match, we can do this with:



    def tokenize(text):
    return filter(None, re.split(r'[ ]+|([!:''".,sn])', text))


    For your given sample text, this produces:



    >>> list(tokenize("I am very hungry, so mum brings me a cake!n"))
    ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





    share|improve this answer




















    • why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
      – SoManyProblems
      Nov 10 at 14:01










    • @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
      – Willem Van Onsem
      Nov 10 at 14:02










    • thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
      – SoManyProblems
      Nov 10 at 14:42










    • @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
      – Willem Van Onsem
      Nov 10 at 14:43














    up vote
    1
    down vote













    That is because your regular expression contains a capture group. Because of that capture group, it will also include the matches in the result. But this is likely what you want.



    The only challenge is to filter out the Nones (and other values with truthiness False) in case there is no match, we can do this with:



    def tokenize(text):
    return filter(None, re.split(r'[ ]+|([!:''".,sn])', text))


    For your given sample text, this produces:



    >>> list(tokenize("I am very hungry, so mum brings me a cake!n"))
    ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





    share|improve this answer




















    • why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
      – SoManyProblems
      Nov 10 at 14:01










    • @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
      – Willem Van Onsem
      Nov 10 at 14:02










    • thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
      – SoManyProblems
      Nov 10 at 14:42










    • @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
      – Willem Van Onsem
      Nov 10 at 14:43












    up vote
    1
    down vote










    up vote
    1
    down vote









    That is because your regular expression contains a capture group. Because of that capture group, it will also include the matches in the result. But this is likely what you want.



    The only challenge is to filter out the Nones (and other values with truthiness False) in case there is no match, we can do this with:



    def tokenize(text):
    return filter(None, re.split(r'[ ]+|([!:''".,sn])', text))


    For your given sample text, this produces:



    >>> list(tokenize("I am very hungry, so mum brings me a cake!n"))
    ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





    share|improve this answer












    That is because your regular expression contains a capture group. Because of that capture group, it will also include the matches in the result. But this is likely what you want.



    The only challenge is to filter out the Nones (and other values with truthiness False) in case there is no match, we can do this with:



    def tokenize(text):
    return filter(None, re.split(r'[ ]+|([!:''".,sn])', text))


    For your given sample text, this produces:



    >>> list(tokenize("I am very hungry, so mum brings me a cake!n"))
    ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 10 at 11:58









    Willem Van Onsem

    141k16132225




    141k16132225











    • why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
      – SoManyProblems
      Nov 10 at 14:01










    • @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
      – Willem Van Onsem
      Nov 10 at 14:02










    • thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
      – SoManyProblems
      Nov 10 at 14:42










    • @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
      – Willem Van Onsem
      Nov 10 at 14:43
















    • why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
      – SoManyProblems
      Nov 10 at 14:01










    • @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
      – Willem Van Onsem
      Nov 10 at 14:02










    • thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
      – SoManyProblems
      Nov 10 at 14:42










    • @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
      – Willem Van Onsem
      Nov 10 at 14:43















    why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
    – SoManyProblems
    Nov 10 at 14:01




    why adding the [ ]+| into the reg expression would lead to generating a lot of Nones ? I
    – SoManyProblems
    Nov 10 at 14:01












    @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
    – Willem Van Onsem
    Nov 10 at 14:02




    @SoManyProblems: because if the capture group (the part in the parenthesis), does not matches anything, it still introduces a None for "empty" capture groups. If you generate multiple parenthesis, this can even result in a lot of extra elements.
    – Willem Van Onsem
    Nov 10 at 14:02












    thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
    – SoManyProblems
    Nov 10 at 14:42




    thanks a lot for the reply. Just to confirm that I understand you correctly, do you mean that [ ]+ matches the space, so it did the split work, and because it doesn't have a (), so it would returns None back ?
    – SoManyProblems
    Nov 10 at 14:42












    @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
    – Willem Van Onsem
    Nov 10 at 14:43




    @SoManyProblems: the regex itself has a (...), a capture group. But since that capture group is not "activated" (it ddoes not matches anything), it captures None.
    – Willem Van Onsem
    Nov 10 at 14:43










    up vote
    1
    down vote













    One approach is to surround the special characters (,!.n) with space and then split on space:



    import re


    def tokenize(t, pattern="([,!.n])"):
    return [e for e in re.sub(pattern, r" 1 ", t).split(' ') if e]


    s = "I am very hungry, so mum brings me a cake!n"

    print(tokenize(s))


    Output



    ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





    share|improve this answer
























      up vote
      1
      down vote













      One approach is to surround the special characters (,!.n) with space and then split on space:



      import re


      def tokenize(t, pattern="([,!.n])"):
      return [e for e in re.sub(pattern, r" 1 ", t).split(' ') if e]


      s = "I am very hungry, so mum brings me a cake!n"

      print(tokenize(s))


      Output



      ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





      share|improve this answer






















        up vote
        1
        down vote










        up vote
        1
        down vote









        One approach is to surround the special characters (,!.n) with space and then split on space:



        import re


        def tokenize(t, pattern="([,!.n])"):
        return [e for e in re.sub(pattern, r" 1 ", t).split(' ') if e]


        s = "I am very hungry, so mum brings me a cake!n"

        print(tokenize(s))


        Output



        ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']





        share|improve this answer












        One approach is to surround the special characters (,!.n) with space and then split on space:



        import re


        def tokenize(t, pattern="([,!.n])"):
        return [e for e in re.sub(pattern, r" 1 ", t).split(' ') if e]


        s = "I am very hungry, so mum brings me a cake!n"

        print(tokenize(s))


        Output



        ['I', 'am', 'very', 'hungry', ',', 'so', 'mum', 'brings', 'me', 'a', 'cake', '!', 'n']






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 12:02









        Daniel Mesejo

        10.1k1923




        10.1k1923



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238662%2fpython-re-split-how-to-save-some-of-the-delimiters-instead-of-all-the-delimi%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Syphilis

            Darth Vader #20