pythonpython-3.xjupyter-notebooknltknltk-book

Python : AttributeError: 'NoneType' object has no attribute 'start'


The below code belongs to NLTK regex:

import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize

scene = "Hello how! how are you? what is your problem. Can I solve with 00code for you/ by the way bye. Take care"

match_index = print(re.search("you",scene))
print(match_index.start(),match_index.end())

Error I got is:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-54-5e13e5437c3e> in <module>()
----> 1 print(match_index.start(),match_index.end())

AttributeError: 'NoneType' object has no attribute 'start'

I have included its library but still, it is showing an error. What are the ways I can handle this error?


Solution

  • match_index = print(re.search("you",scene))
    

    print returns None, so after this line, match_index is None.

    Try assigning and printing on separate lines.

    match_index = re.search("you",scene)
    print(match_index)
    

    Result:

    <_sre.SRE_Match object; span=(19, 22), match='you'>
    19 22