The goal is to deal with the task of tokenization in NLP and porting the script from the Perl script to this Python script.
The main issues comes with erroneous backslashes that happens when we run the Python port of the tokenizer.
In Perl, we could need to escape the single quotes and the ampersand as such:
my($text) = @_; # Reading a text from stdin
$text =~ s=n't = n't =g; # Puts a space before the "n't" substring to tokenize english contractions like "don't" -> "do n't".
$text =~ s/\'/\'/g; # Escape the single quote so that it suits XML.
Porting the regex literally into Python
>>> import re
>>> from six import text_type
>>> sent = text_type("this ain't funny")
>>> escape_singquote = r"\'", r"\'" # escape the left quote for XML
>>> contraction = r"n't", r" n't" # pad a space on the left when "n't" pattern is seen
>>> text = sent
>>> for regexp, substitution in [contraction, escape_singquote]:
... text = re.sub(regexp, substitution, text)
... print text
...
this ai n't funny
this ai n\'t funny
The escaping of the ampersand somehow added it as a literal backslash =(
To resolve that, I could do:
>>> escape_singquote = r"\'", r"'" # escape the left quote for XML
>>> text = sent
>>> for regexp, substitution in [contraction, escape_singquote]:
... text = re.sub(regexp, substitution, text)
... print text
...
this ai n't funny
this ai n't funny
But seemingly without escaping the single quote in Python, we get the desired result too:
>>> import re
>>> from six import text_type
>>> sent = text_type("this ain't funny")
>>> escape_singquote = r"\'", r"\'" # escape the left quote for XML
>>> contraction = r"n't", r" n't" # pad a space on the left when "n't" pattern is seen
>>> escape_singquote = r"'", r"'" # escape the left quote for XML
>>> text = sent
>>> for regexp, substitution in [contraction, escape_singquote]:
... text = re.sub(regexp, substitution, text)
... print text
...
this ai n't funny
this ai n't funny
Now that's puzzling...
Given the context above, so the question is for which characters do we need to escape in Python and which characters in Perl? Regex in Perl and Python is not that equivalent right?