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