spaCy icon indicating copy to clipboard operation
spaCy copied to clipboard

Strange splitting with prefix/suffix tokenizer's rules

Open damianoporta opened this issue 9 years ago • 4 comments

Your Environment

  • Operating System: Ubuntu 16.04
  • Python Version Used: 3.5.2
  • spaCy Version Used: develop branch

Hello, i have found another problem with tokenization. Take a look at this example:

# coding: utf8
import spacy
import re
from spacy.tokenizer import Tokenizer

prefix_re = re.compile(r'''[\[\("']''')
suffix_re = re.compile(r'''[\]\)"']''')
infix_re = re.compile(r'''[-~]''')

def my_tokenizer(nlp):
    return Tokenizer(nlp.vocab,
                     {},
                     prefix_search=prefix_re.search,
                     suffix_search=suffix_re.search,
                     infix_finditer=infix_re.finditer)

nlp = spacy.load('en')
nlp.tokenizer = my_tokenizer(nlp)

doc = nlp("This is a test with single quote 'goodbye end.")

for token in doc:
    print(token.text)

the result is:

This
is
a
test
with
single
quote
'
goodby
e
end.

There is a strange split on "goodbye" word because there is no single quote at the end(suffix). Is this a bug?

damianoporta avatar Nov 03 '17 20:11 damianoporta

Oh wow, okay, this definitely looks suspicious and like an off-by-one error somewhere. Just adding a test to check this.

ines avatar Nov 03 '17 20:11 ines

Okay, I think we figured it out: spaCy lets you pass in any function for the prefix and suffix rules and not just regular expressions (which is also why you're passing in the search function prefix_re.search and not just the expression).

But this also means that you need to make sure that the prefix rules match at the beginning of a string, and the suffix rules match at the end of a string. There's no way for spaCy to interject and make this happen – it just calls the function you supplied. So you'll have to change your prefix and suffix rules to take the start / end into account:

prefix_re = re.compile(r'''^[\[\("']''')
suffix_re = re.compile(r'''[\]\)"']$''')

Edit: Maybe we should add a warning to the docs about this.

ines avatar Nov 03 '17 20:11 ines

Could you add this to the example on https://spacy.io/docs/usage/customizing-tokenizer ? It would have saved me a couple of hours of reading the underlying code :)

hodsonjames avatar Nov 07 '17 04:11 hodsonjames

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar May 08 '18 11:05 lock[bot]