pythonpython-3.xfile-iotypeerrorstanford-nlp

TypeError: stat: path should be string, bytes, os.PathLike or integer, not _io.TextIOWrapper


I found the following code on a python tutorial website:

from nltk.tag import StanfordNERTagger

stanford_classifier = open("english.all.3class.distsim.crf.ser.gz")
stanford_ner_path = open("stanford-ner.jar")

st = StanfordNERTagger(stanford_classifier, stanford_ner_path)

The error is as follows:

Traceback (most recent call last):
  File "C:/Users/DELL7810/AppData/Local/Programs/Python/Python37/stanpar.py", line 9, in <module>
st = StanfordNERTagger(stanford_classifier, stanford_ner_path)
 File "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tag\stanford.py", line 180, in __init__
super(StanfordNERTagger, self).__init__(*args, **kwargs)
File "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\tag\stanford.py", line 63, in __init__
verbose=verbose)
File "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\internals.py", line 721, in find_jar
searchpath, url, verbose, is_regex))
File "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\lib\site-packages\nltk\internals.py", line 632, in find_jar_iter
if os.path.isfile(path_to_jar):
File "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\lib\genericpath.py", line 30, in isfile
st = os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not _io.TextIOWrapper

Solution

  • Your problem

    As you can see in this documentation page, StanfordNERTagger takes file paths as arguments:

    StanfordNERTagger(path_to_model, path_to_jar)
    

    Your code crashes because open() will give you file objects and this is not what StanfordNERTagger is expecting as arguments.

    Solution

    Directly give your paths as arguments to StanfordNERTagger, like this:

    st = StanfordNERTagger("C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\stanford-ner-2018-02-27\classifiers\english.all.3class.distsim.crf.ser.gz", "C:\Users\DELL7810\AppData\Local\Programs\Python\Python37\stanford-ner-2018-02-27\stanford-ner.jar")