Use py-corenlp https://github.com/smilli/py-corenlp/
下载斯坦福核心自然语言处理 http://stanfordnlp.github.io/CoreNLP/
此时(2020-05-25)最新版本是4.0.0:
wget https://nlp.stanford.edu/software/stanford-corenlp-4.0.0.zip https://nlp.stanford.edu/software/stanford-corenlp-4.0.0-models-english.jar
如果你没有wget https://www.gnu.org/software/wget/,你可能有curl https://curl.haxx.se/:
curl https://nlp.stanford.edu/software/stanford-corenlp-4.0.0.zip -O https://nlp.stanford.edu/software/stanford-corenlp-4.0.0-models-english.jar -O
如果其他方法都失败,请使用浏览器;-)
安装包
unzip stanford-corenlp-4.0.0.zip
mv stanford-corenlp-4.0.0-models-english.jar stanford-corenlp-4.0.0
开始server http://stanfordnlp.github.io/CoreNLP/corenlp-server.html
cd stanford-corenlp-4.0.0
java -mx5g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -timeout 10000
Notes:
-
timeout
单位是毫秒,我上面设置为10秒。
如果将巨大的 blob 传递到服务器,则应该增加它。
- 有更多的选择 https://stanfordnlp.github.io/CoreNLP/corenlp-server.html#command-line-flags,你可以列出它们
--help
.
-
-mx5g
应该分配足够的memory https://stackoverflow.com/q/14763079/850781,但是YMMV,如果您的盒子动力不足,您可能需要修改该选项。
安装python包
标准套餐
pip install pycorenlp
does not使用Python 3.9,所以你需要做
pip install git+https://github.com/sam-s/py-corenlp.git
(也可以看看官方名单 https://stanfordnlp.github.io/CoreNLP/other-languages.html).
Use it
from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
res = nlp.annotate("I love you. I hate him. You are nice. He is dumb",
properties={
'annotators': 'sentiment',
'outputFormat': 'json',
'timeout': 1000,
})
for s in res["sentences"]:
print("%d: '%s': %s %s" % (
s["index"],
" ".join([t["word"] for t in s["tokens"]]),
s["sentimentValue"], s["sentiment"]))
你会得到:
0: 'I love you .': 3 Positive
1: 'I hate him .': 1 Negative
2: 'You are nice .': 3 Positive
3: 'He is dumb': 1 Negative
Notes
- 您将整个文本传递给服务器,服务器将其分割成句子。它还将句子分割成标记。
- 感情归于每个人sentence,不是全文. The mean https://en.wikipedia.org/wiki/Mean
sentimentValue
跨句子可以用来估计整个文本的情绪。
- 一个句子的平均情绪介于
Neutral
(2和Negative
(1)、取值范围为VeryNegative
(0) to VeryPositive
(4) 看起来相当罕见。
- You can stop the server https://stanfordnlp.github.io/CoreNLP/corenlp-server.html#stopping-the-server either by typing Ctrl-C at the terminal you started it from or using the shell command
kill $(lsof -ti tcp:9000)
. 9000
is the default port, you can change it using the -port
option when starting the server.
- 增加
timeout
(以毫秒为单位)在服务器或客户端中如果出现超时错误。
-
sentiment
只是one注释器,有还有很多 https://stanfordnlp.github.io/CoreNLP/annotators.html,您可以请求多个,用逗号分隔:'annotators': 'sentiment,lemma'
.
- 请注意,情绪模型有些特殊(例如,根据你提到的是大卫还是比尔,结果会有所不同 https://github.com/stanfordnlp/CoreNLP/issues/351).
PS。我不敢相信我添加了一个9th答案,但是,我想,我必须这样做,因为现有的答案都没有帮助我(之前的 8 个答案中的一些现已被删除,其他一些已转换为评论)。