Good day SO,
I am trying to post-process hyphenated words that are tokenized into separate tokens when they were supposedly a single token. For example:
Example:
Sentence: "up-scaled"
Tokens: ['up', '-', 'scaled']
Expected: ['up-scaled']
For now, my solution is to use the matcher:
matcher = Matcher(nlp.vocab)
pattern = [{'IS_ALPHA': True, 'IS_SPACE': False},
{'ORTH': '-'},
{'IS_ALPHA': True, 'IS_SPACE': False}]
matcher.add('HYPHENATED', None, pattern)
def quote_merger(doc):
# this will be called on the Doc object in the pipeline
matched_spans = []
matches = matcher(doc)
for match_id, start, end in matches:
span = doc[start:end]
matched_spans.append(span)
for span in matched_spans: # merge into one token after collecting all matches
span.merge()
#print(doc)
return doc
nlp.add_pipe(quote_merger, first=True) # add it right after the tokenizer
doc = nlp(text)
However, this will cause an expected issue below:
Example 2:
Sentence: "I know I will be back - I had a very pleasant time"
Tokens: ['i', 'know', 'I', 'will', 'be', 'back - I', 'had', 'a', 'very', 'pleasant', 'time']
Expected: ['i', 'know', 'I', 'will', 'be', 'back', '-', 'I', 'had', 'a', 'very', 'pleasant', 'time']
Is there a way where I can process only words separated by hyphens that do not have spaces between the characters? So that words like 'up-scaled' will be matched and combined into a single token, but not '.. back - I ..'
Thank you very much
EDIT: I have tried the solution posted: Why does spaCy not preserve intra-word-hyphens during tokenization like Stanford CoreNLP does?
However, I didn't use this solution because it resulted in wrong tokenization of words with apostrophes (') and Numbers with decimals:
Sentence: "It's"
Tokens: ["I", "t's"]
Expected: ["It", "'s"]
Sentence: "1.50"
Tokens: ["1", ".", "50"]
Expected: ["1.50"]
That is why I used Matcher instead of trying to edit the regex.