TL; DR
設置一個不同的_SEPARATOR
:
from nltk.tag import StanfordPOSTagger
st = StanfordPOSTagger('chinese-distsim.tagger')
st._SEPARATOR = '#'
print(st.tag('這 是 斯坦福 中文 分詞器 測試'.split()))
更好的解決方案
持幣觀望了一段時間,等待NLTK v3.2.5那裏將是一個非常與不同語言標準化的Stanford標記器的簡單接口。
再也沒有定界符由於標記和標記是通過從一個REST接口一個JSON傳送參與=)
此外,StanfordSegmenter
和StanfordTokenizer
類將被在v3.2.5棄用,見
首先升級nltk
版本:
下載並啓動斯坦福CoreNLP服務器:在NLTK v3.2.5
wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31
wget http://nlp.stanford.edu/software/stanford-chinese-corenlp-2016-10-31-models.jar
wget https://raw.githubusercontent.com/stanfordnlp/CoreNLP/master/src/edu/stanford/nlp/pipeline/StanfordCoreNLP-chinese.properties
java -Xmx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
-serverProperties StanfordCoreNLP-chinese.properties \
-preload tokenize,ssplit,pos,lemma,ner,parse \
-status_port 9001 -port 9001 -timeout 15000
然後:
>>> from nltk.tag.stanford import CoreNLPPOSTagger, CoreNLPNERTagger
>>> from nltk.tokenize.stanford import CoreNLPTokenizer
>>> stpos, stner = CoreNLPPOSTagger('http://localhost:9001'), CoreNLPNERTagger('http://localhost:9001')
>>> sttok = CoreNLPTokenizer('http://localhost:9001')
>>> sttok.tokenize(u'我家沒有電腦。')
['我家', '沒有', '電腦', '。']
# Without segmentation (input to`raw_string_parse()` is a list of single char strings)
>>> stpos.tag(u'我家沒有電腦。')
[('我', 'PN'), ('家', 'NN'), ('沒', 'AD'), ('有', 'VV'), ('電', 'NN'), ('腦', 'NN'), ('。', 'PU')]
# With segmentation
>>> stpos.tag(sttok.tokenize(u'我家沒有電腦。'))
[('我家', 'NN'), ('沒有', 'VE'), ('電腦', 'NN'), ('。', 'PU')]
# Without segmentation (input to`raw_string_parse()` is a list of single char strings)
>>> stner.tag(u'奧巴馬與邁克爾·傑克遜一起去雜貨店購物。')
[('奧', 'GPE'), ('巴', 'GPE'), ('馬', 'GPE'), ('與', 'O'), ('邁', 'O'), ('克', 'PERSON'), ('爾', 'PERSON'), ('·', 'O'), ('傑', 'O'), ('克', 'O'), ('遜', 'O'), ('一', 'NUMBER'), ('起', 'O'), ('去', 'O'), ('雜', 'O'), ('貨', 'O'), ('店', 'O'), ('購', 'O'), ('物', 'O'), ('。', 'O')]
# With segmentation
>>> stner.tag(sttok.tokenize(u'奧巴馬與邁克爾·傑克遜一起去雜貨店購物。'))
[('奧巴馬', 'PERSON'), ('與', 'O'), ('邁克爾·傑克遜', 'PERSON'), ('一起', 'O'), ('去', 'O'), ('雜貨店', 'O'), ('購物', 'O'), ('。', 'O')]
好現在的工作,謝謝。但是爲什麼在文檔中沒有提到這一點?修改一個以下劃線開頭的變量看起來頗爲冒險。 – yhylord
實際上'StanfordPOSTagger'將在下一個NLTK版本中被棄用,請使用新的'CoreNLPPOSTagger',請參閱https://github.com/nltk/nltk/pull/1735 – alvas
特別適用於中文https://github.com/nltk/nltk/pull/1735#issuecomment-306137326 – alvas