-
Notifications
You must be signed in to change notification settings - Fork 11
/
StanfordCoreNLP.py
executable file
·1065 lines (951 loc) · 58.5 KB
/
StanfordCoreNLP.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-*- coding: utf-8 -*-
#!python3
import langdetect
from stanza.server import CoreNLPClient
'''
For reference
Download and Install Stanford CoreNLP:
https://stanfordnlp.github.io/CoreNLP/download.html
Official Python implementation is stanza:
https://stanfordnlp.github.io/CoreNLP/other-languages.html#python
Penn Treebank POS tags:
https://repository.upenn.edu/cgi/viewcontent.cgi?article=1039&context=ircs_reports
Stanza basic usage of CoreNLP client:
https://stanfordnlp.github.io/stanza/client_usage.html
Stanford NLP dependencies manual:
https://nlp.stanford.edu/software/dependencies_manual.pdf
Setting the CoreNLP root folder as environment variable
use .bash_profile
export CLASSPATH=$CLASSPATH:/usr/local/StanfordCoreNLP/stanford-corenlp-4.1.0/*:
CORENLP_HOME="/usr/local/StanfordCoreNLP/stanford-corenlp-4.1.0"
for file in `find $CORENLP_HOME/ -name "*.jar"`;
do export CLASSPATH="$CLASSPATH:`realpath $file`"; done
#### if you need to use the CORENLP_HOME path for something:
corenlp_home = os.environ['CORENLP_HOME']
##############################
#### Annotators explained ####
##############################
# default annotators is all: annotators=['tokenize','ssplit','pos','lemma','ner', 'parse', 'depparse','coref']
# tokenize: splits each word
# ssplit: splits the structure by sentence in a list of sentences.
# pos: Part of Speech tagging
# lemma: Lemmatizes the words to a basic conjugation/ dictionary form
# ner: Named Entity Recognizer
# parse: Parsing
# depparse: Dependency Parsing
# coref: Coreference Resolution
########### For English
# stanford-corenlp-4.1.0-models-english.jar
# properties are the default
# Examples of use:
def example_English():
text = 'This is a test sentence for the server to handle. I wonder what it will do.'
with CoreNLPClient(
annotators=None,
#['tokenize','ssplit','pos','lemma','ner', 'parse', 'depparse','coref'],
properties=None,
#{
#'tokenize_pretokenized': True, # Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
#'tokenize_no_ssplit':True # Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
#}, #You can add more or just use None
timeout=150000
) as client:
ann = client.annotate(text)
# ann is a Document class, broken down in Sentence objects, which each have Token objects inside.
# For example, to take the list of tokenized words out:
len(ann.sentence)
# 2
sent_list = [token.word for token in ann.sentence[0].token]
# ['This', 'is', 'a', 'test', 'sentence', 'for', 'the', 'server', 'to', 'handle','.']
sent_list = [token.word for token in ann.sentence[1].token]
# ['I', 'wonder', 'what', 'it', 'will', 'do','.']
########### For Chinese
# properties from StanfordCoreNLP-chinese.properties
# Examples of use:
def example_Chinese():
text = "国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"
# Taken from stanford-corenlp-4.1.0-models-chinese.jar
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
with CoreNLPClient(
annotators=None,
properties=properties, # properties from StanfordCoreNLP-chinese.properties
timeout=15000
) as client:
ann = client.annotate(text)
sent_list = [token.word for token in ann.sentence[0].token]
# ['国务院', '日前', '发出', '紧急', '通知', ',', '要求', '各地', '切实', '落实', '保证', '市场', '供应', '的', '各', '项', '政策', ',', '维护', '副食品', '价格', '稳定', '。']
'''
def get_StanfordCoreNLP_chinese_properties(properties=None):
'''
Exports properties taken from stanford-corenlp-4.1.0-models-chinese.jar to be able to run the Chinese models with the python client.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:return: Properties enabling Chinese language parsing, in addition to any in parameters.
For example:
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout) as client:
ann = client.annotate(text)
'''
StanfordCoreNLP_chinese_properties = {'annotators':('tokenize', 'ssplit', 'pos', 'lemma', 'ner', 'parse', 'coref'),'tokenize.language':'zh','segment.model':'edu/stanford/nlp/models/segmenter/chinese/ctb.gz','segment.sighanCorporaDict':'edu/stanford/nlp/models/segmenter/chinese','segment.serDictionary':'edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz','segment.sighanPostProcessing':True,'ssplit.boundaryTokenRegex':'[.。]|[!?!?]+','pos.model':'edu/stanford/nlp/models/pos-tagger/chinese-distsim.tagger','ner.language':'chinese','ner.model':'edu/stanford/nlp/models/ner/chinese.misc.distsim.crf.ser.gz','ner.applyNumericClassifiers':True,'ner.useSUTime':False,'ner.fine.regexner.mapping':'edu/stanford/nlp/models/kbp/chinese/gazetteers/cn_regexner_mapping.tab','ner.fine.regexner.noDefaultOverwriteLabels':'CITY,COUNTRY,STATE_OR_PROVINCE','parse.model':'edu/stanford/nlp/models/srparser/chineseSR.ser.gz','depparse.model ':'edu/stanford/nlp/models/parser/nndep/UD_Chinese.gz','depparse.language':'chinese','coref.sieves':'ChineseHeadMatch, ExactStringMatch, PreciseConstructs, StrictHeadMatch1, StrictHeadMatch2, StrictHeadMatch3, StrictHeadMatch4, PronounMatch','coref.input.type':'raw','coref.postprocessing':True,'coref.calculateFeatureImportance':False,'coref.useConstituencyTree':True,'coref.useSemantics':False,'coref.algorithm':'hybrid','coref.path.word2vec':'','coref.language':'zh','coref.defaultPronounAgreement':True,'coref.zh.dict':'edu/stanford/nlp/models/dcoref/zh-attributes.txt.gz','coref.print.md.log':False,'coref.md.type':'RULE','coref.md.liberalChineseMD':False,'kbp.semgrex':'edu/stanford/nlp/models/kbp/chinese/semgrex','kbp.tokensregex':'edu/stanford/nlp/models/kbp/chinese/tokensregex','kbp.language':'zh','kbp.model':None,'entitylink.wikidict':'edu/stanford/nlp/models/kbp/chinese/wikidict_chinese.tsv.gz'}
if properties:
StanfordCoreNLP_chinese_properties.update(properties)
return StanfordCoreNLP_chinese_properties
#############################################################################################
#############################################################################################
#############################################################################################
##### Methods to simplify using the CoreNLP client for specific purposes in my projects #####
#############################################################################################
#############################################################################################
#############################################################################################
##########################
##### Segmentation #######
##########################
def Segment_str_langdetect(text,
sent_split=True,
tolist=True,
properties=None,
timeout=15000,
be_quiet=False,
chinese_only=False):
'''
Processes a string, detects if it is Chinese or English, and returns list of words nested in lists of sentences, or text split by spaces and newlines depending on parameters.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (bool) be_quiet: CoreNLPClient silent mode
:param (bool) chinese_only: set to True to ignore English and other languages. Set to False to process English and Chinese.
Ignoring English can save overhead, when faster tools are available.
:return: segmented text in nested list or string
Example:
en_text = 'This is a test sentence for the server to handle. I wonder what it will do.'
Segment_str_langdetect(en_text, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[['This', 'is', 'a', 'test', 'sentence', 'for', 'the', 'server', 'to', 'handle', '.'], ['I', 'wonder', 'what', 'it', 'will', 'do', '.']]
zh_text = "国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"
Segment_str_langdetect(zh_text, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[['国务院', '日前', '发出', '紧急', '通知', ',', '要求', '各', '地', '切实', '落实', '保证', '市场', '供应', '的', '各', '项', '政策', ',', '维护', '副食品', '价格', '稳定', '。']]
Segment_str_langdetect(zh_text, sent_split=True, tolist=False, properties=None, timeout=15000, chinese_only=False)
>>>'国务院 日前 发出 紧急 通知 , 要求 各 地 切实 落实 保证 市场 供应 的 各 项 政策 , 维护 副食品 价格 稳定 。'
'''
if sent_split:
annotators = ['tokenize', 'ssplit']
else:
annotators = ['tokenize']
words=[]
if text!='':
if not sent_split:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
##########
try:
lang = langdetect.detect(text)
except langdetect.lang_detect_exception.LangDetectException:
lang = "undetermined"
if chinese_only:
parse_ok = (lang == "zh-cn")
else:
parse_ok = (lang == "zh-cn") or (lang == "en")
if parse_ok:
if (lang == "zh-cn"):
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
ann = client.annotate(text)
words = [[token.word for token in sent.token] for sent in ann.sentence]
segmented_list = [' '.join(wordlist) for wordlist in words]
if sent_split:
segmented = '\n'.join(segmented_list)
else:
words = [word for sent in words for word in sent]
segmented = ' '.join(segmented_list)
else:
segmented = text
words = segmented.split()
else:
segmented = text
if tolist:
return words #list
else:
return segmented #string
def Segment(text_list,
sent_split=True,
tolist=True,
properties=None,
timeout=15000,
verbose=1,
lang='zh-cn'):
'''
Processes a list of Chinese or English strings and returns list of words nested in lists of sentences, or a list of text split by spaces and newlines depending on parameters.
It starts the server with the same properties for all texts, so all texts must be the same language, setup by the parameter :lang:. Default is Chinese lang='zh-cn'.
:param (list[str] | tuple[str] | str) text_list: list of strings of raw text for the CoreNLPServer to parse
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (int) verbose: verbose level
0: CoreNLPClient silent mode, no progress printing
1: CoreNLPClient silent mode, progress printing
2: CoreNLPClient silent mode off, no progress printing
3: CoreNLPClient silent mode off, progress printing
:param (str) lang: 'zh-cn' for Chinese and 'en' for English
:return: list of segmented text in nested list or list of strings
Example:
en_texts = ['This is a test sentence for the server to handle. I wonder what it will do.']
Segment(en_texts, sent_split=True, tolist=True, properties=None, timeout=15000, lang='en')
>>>[[['This', 'is', 'a', 'test', 'sentence', 'for', 'the', 'server', 'to', 'handle', '.'], ['I', 'wonder', 'what', 'it', 'will', 'do', '.']]]
zh_texts = ["国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"]
Segment(zh_texts, sent_split=True, tolist=True, properties=None, timeout=15000, lang='zh-cn')
>>>[[['国务院', '日前', '发出', '紧急', '通知', ',', '要求', '各', '地', '切实', '落实', '保证', '市场', '供应', '的', '各', '项', '政策', ',', '维护', '副食品', '价格', '稳定', '。']]]
Segment(zh_texts, sent_split=True, tolist=False, properties=None, timeout=15000, lang='zh-cn')
>>>[['国务院 日前 发出 紧急 通知 , 要求 各 地 切实 落实 保证 市场 供应 的 各 项 政策 , 维护 副食品 价格 稳定 。']]
'''
if type(text_list)==type(''):
text_list = [text_list]
if not sent_split:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
if (lang == "zh-cn"):
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
if sent_split:
annotators = ['tokenize', 'ssplit']
else:
annotators = ['tokenize']
if verbose == 0:
be_quiet = True
print_progress = False
elif verbose == 1:
be_quiet = True
print_progress = True
elif verbose == 2:
be_quiet = False
print_progress = False
elif verbose == 3:
be_quiet = False
print_progress = True
else:
be_quiet = False
print_progress = True
result = []
limit = len(text_list)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
for i ,text in enumerate(text_list):
if print_progress:
if lang=='zh-cn':
print("Segmenting Chinese sentence {} of {}".format(i+1,limit))
elif lang=='en':
print("SegmentingEnglish sentence {} of {}".format(i+1,limit))
if text!='':
ann = client.annotate(text)
words = [[token.word for token in sent.token] for sent in ann.sentence]
segmented_list = [' '.join(wordlist) for wordlist in words]
if sent_split:
segmented = '\n'.join(segmented_list)
else:
words = [word for sent in words for word in sent]
segmented = ' '.join(segmented_list)
else:
segmented = text
words=[]
if tolist:
result.append(words) #list
else:
result.append(segmented) #string
return result
#########################
##### POS Tagging #######
#########################
def POS_Tag_str_langdetect(text,
sent_split=True,
pre_tokenized=True,
tolist=True,
properties=None,
timeout=15000,
be_quiet=False,
chinese_only=False):
'''
Processes a string, detects if it is Chinese or English, and returns a list of words paired in tuples with their tags, nested in lists of sentences;
or text split by spaces and newlines depending on parameters, tagged delimited by #.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) pre_tokenized: Avoids loading the tokenizer if true. Assumes previously split words by spaces and sentences by newlines.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (bool) be_quiet: CoreNLPClient silent mode
:param (bool) chinese_only: set to True to ignore English and other languages. Set to False to process English and Chinese.
POS Tags explanation
The Chinese tags used by Stanford NLP are the same as Penn Treebank POS Tags
Penn Treebank POS tags:
https://repository.upenn.edu/cgi/viewcontent.cgi?article=1039&context=ircs_reports
:return: segmented pairs of (word, tag) nested in sentences
[ [(token, pos_tag), (token, pos_tag)],
[(token, pos_tag), (token, pos_tag)],
]
or string tagged by #, sentences delimited by newline.
"token#pos_tag token#pos_tag
token#pos_tag token#pos_tag"
Example:
en_text = 'This is a test sentence for the server to handle. I wonder what it will do.'
POS_Tag_str_langdetect(en_text, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), ('sentence', 'NN'), ('for', 'IN'), ('the', 'DT'), ('server', 'NN'), ('to', 'TO'), ('handle', 'VB'), ('.', '.')], [('I', 'PRP'), ('wonder', 'VBP'), ('what', 'WP'), ('it', 'PRP'), ('will', 'MD'), ('do', 'VB'), ('.', '.')]]
zh_text = "国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"
POS_Tag_str_langdetect(zh_text, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[[('国务院', 'NN'), ('日前', 'NT'), ('发出', 'VV'), ('紧急', 'JJ'), ('通知', 'NN'), (',', 'PU'), ('要求', 'VV'), ('各', 'DT'), ('地', 'NN'), ('切实', 'AD'), ('落实', 'VV'), ('保证', 'VV'), ('市场', 'NN'), ('供应', 'NN'), ('的', 'DEG'), ('各', 'DT'), ('项', 'M'), ('政策', 'NN'), (',', 'PU'), ('维护', 'VV'), ('副食品', 'NN'), ('价格', 'NN'), ('稳定', 'NN'), ('。', 'PU')]]
POS_Tag_str_langdetect(zh_text, sent_split=True, tolist=False, properties=None, timeout=15000, chinese_only=False)
>>>'国务院#NN 日前#NT 发出#VV 紧急#JJ 通知#NN ,#PU 要求#VV 各#DT 地#NN 切实#AD 落实#VV 保证#VV 市场#NN 供应#NN 的#DEG 各#DT 项#M 政策#NN ,#PU 维护#VV 副食品#NN 价格#NN 稳定#NN 。#PU'
'''
annotators = ['pos']
words=[]
if text!='':
if pre_tokenized:
if not properties:
properties={'tokenize_pretokenized': True}
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
else:
properties.update({'tokenize_pretokenized': True})
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
if sent_split==False:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
##########
try:
lang = langdetect.detect(text)
except langdetect.lang_detect_exception.LangDetectException:
lang = "undetermined"
if chinese_only:
parse_ok = (lang == "zh-cn")
else:
parse_ok = (lang == "zh-cn") or (lang == "en")
if parse_ok:
if (lang == "zh-cn"):
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
ann = client.annotate(text)
words = [[(token.word,token.pos) for token in sent.token] for sent in ann.sentence]
segmented_list = [' '.join(['#'.join(posted) for posted in wordlist]) for wordlist in words]
if sent_split:
segmented = '\n'.join(segmented_list)
else:
words = [(word,pos) for sent in words for word,pos in sent]
segmented = ' '.join(segmented_list)
else:
segmented = text
words = segmented.split()
else:
segmented = text
if tolist:
return words #list
else:
return segmented #string
def POS_Tag(text_list,
sent_split=True,
pre_tokenized=True,
tolist=True,
properties=None,
timeout=15000,
verbose=1,
lang='zh-cn'):
'''
Processes a list of Chinese or English strings and returns lists of words paired in tuples with their tags, nested in lists of sentences, nested in lists of documents in text_list;
or lists of text split by spaces and newlines depending on parameters, tagged delimited by #.
It starts the server with the same properties for all texts, so all texts must be the same language, setup by the parameter :lang:. Default is Chinese lang='zh-cn'.
:param (list[str] | tuple[str] | str) text_list: list of strings of raw text for the CoreNLPServer to parse
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) pre_tokenized: Avoids loading the tokenizer if true. Assumes previously split words by spaces and sentences by newlines.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (int) verbose: verbose level
0: CoreNLPClient silent mode, no progress printing
1: CoreNLPClient silent mode, progress printing
2: CoreNLPClient silent mode off, no progress printing
3: CoreNLPClient silent mode off, progress printing
:param (str) lang: 'zh-cn' for Chinese and 'en' for English
POS Tags explanation
The Chinese tags used by Stanford NLP are the same as Penn Treebank POS Tags
Penn Treebank POS tags:
https://repository.upenn.edu/cgi/viewcontent.cgi?article=1039&context=ircs_reports
:return: segmented pairs of (word, tag) nested in sentences, nested in documents (determined at input)
[[ [(token, pos_tag), (token, pos_tag)],
[(token, pos_tag), (token, pos_tag)],
], # per document
...]
or list of strings tagged by #, sentences delimited by newline.
["token#pos_tag token#pos_tag
token#pos_tag token#pos_tag",...]
Example:
en_texts = ['This is a test sentence for the server to handle. I wonder what it will do.']
POS_Tag(en_texts, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[[[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('test', 'NN'), ('sentence', 'NN'), ('for', 'IN'), ('the', 'DT'), ('server', 'NN'), ('to', 'TO'), ('handle', 'VB'), ('.', '.')], [('I', 'PRP'), ('wonder', 'VBP'), ('what', 'WP'), ('it', 'PRP'), ('will', 'MD'), ('do', 'VB'), ('.', '.')]]]
zh_texts = ["国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"]
POS_Tag(zh_texts, sent_split=True, tolist=True, properties=None, timeout=15000, chinese_only=False)
>>>[[[('国务院', 'NN'), ('日前', 'NT'), ('发出', 'VV'), ('紧急', 'JJ'), ('通知', 'NN'), (',', 'PU'), ('要求', 'VV'), ('各', 'DT'), ('地', 'NN'), ('切实', 'AD'), ('落实', 'VV'), ('保证', 'VV'), ('市场', 'NN'), ('供应', 'NN'), ('的', 'DEG'), ('各', 'DT'), ('项', 'M'), ('政策', 'NN'), (',', 'PU'), ('维护', 'VV'), ('副食品', 'NN'), ('价格', 'NN'), ('稳定', 'NN'), ('。', 'PU')]]]
POS_Tag(zh_texts, sent_split=True, tolist=False, properties=None, timeout=15000, chinese_only=False)
>>>['国务院#NN 日前#NT 发出#VV 紧急#JJ 通知#NN ,#PU 要求#VV 各#DT 地#NN 切实#AD 落实#VV 保证#VV 市场#NN 供应#NN 的#DEG 各#DT 项#M 政策#NN ,#PU 维护#VV 副食品#NN 价格#NN 稳定#NN 。#PU']
'''
if type(text_list)==type(''):
text_list = [text_list]
if pre_tokenized:
if not properties:
properties={'tokenize_pretokenized': True}
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
else:
properties.update({'tokenize_pretokenized': True})
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
if sent_split==False:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
if (lang == "zh-cn"):
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
annotators = ['pos']
if verbose == 0:
be_quiet = True
print_progress = False
elif verbose == 1:
be_quiet = True
print_progress = True
elif verbose == 2:
be_quiet = False
print_progress = False
elif verbose == 3:
be_quiet = False
print_progress = True
else:
be_quiet = False
print_progress = True
result = []
limit = len(text_list)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
for i ,text in enumerate(text_list):
if print_progress:
if lang=='zh-cn':
print("POS Tagging Chinese sentence {} of {}".format(i+1,limit))
elif lang=='en':
print("POS Tagging English sentence {} of {}".format(i+1,limit))
if text!='':
ann = client.annotate(text)
words = [[(token.word,token.pos) for token in sent.token] for sent in ann.sentence]
segmented_list = [' '.join(['#'.join(posted) for posted in wordlist]) for wordlist in words]
if sent_split:
segmented = '\n'.join(segmented_list)
else:
words = [(word,pos) for sent in words for word,pos in sent]
segmented = ' '.join(segmented_list)
else:
segmented = text
words=[]
if tolist:
result.append(words) #list
else:
result.append(segmented) #string
return result
def POS_Tag_str_tolist(pos_tag_str):
'''
In case of storing POS tags output from the method POS_Tag() in string form,
this method returns it to nested list form.
:param (str) pos_tag_str: POS tags string, sentences delimited by newline, in format:
"token#pos_tag token#pos_tag
token#pos_tag token#pos_tag"
:return: POS tagged text in format:
[ [(token, pos_tag), (token, pos_tag)],
[(token, pos_tag), (token, pos_tag)],
]
'''
pos_tag_sentences = pos_tag_str.split('\n')
pos_tag_tups = [sent.split(' ') for sent in pos_tag_sentences]
pos_tags = [[tuple(tup.split('#')) for tup in sent] for sent in pos_tag_tups]
return pos_tags
################################
##### Dependency Parsing #######
################################
########################
'''
Dependency parsing is a bit harder, here's an example:
en_text = 'This is a nice sentence for the server to handle. I wonder what it will do.'
with CoreNLPClient(annotators=['tokenize', 'ssplit', 'lemma', 'pos', 'depparse'],
properties=None,
timeout=15000) as client:
ann = client.annotate(en_text)
sentence = ann.sentence[0]
print(sentence.basicDependencies)
Now let's explain the result. Each node is a word, the index is its number in the sentence.
Each edge is a connection between the words. Let's look at the edge between 5 and 4:
# edge {
# source: 5 # which is 'sentence'
# target: 4 # which is 'nice'
# dep: "amod" # "amod" means adjective modifier
# isExtra: False #
# sourceCopy: 0
# targetCopy: 0
# language: UniversalEnglish
# }
'''
########################
def Dependency_Parse_str_langdetect(text,
dependency_type='basicDependencies',
sent_split=False,
pre_tokenized=True,
tolist=True,
output_with_sentence=True,
properties=None,
timeout=15000,
be_quiet=False,
chinese_only=False):
'''
Processes a string, detects if it is Chinese or English, and collects the dependency, source word and target word in a list of tuples nested in a list of sentences.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (str) dependency_type: Choose from the options Stanford NLP has available. Default basicDependencies.
'alternativeDependencies'
'basicDependencies'
'collapsedCCProcessedDependencies'
'collapsedDependencies'
'enhancedDependencies'
'enhancedPlusPlusDependencies'
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) pre_tokenized: Avoids loading the tokenizer if true. Assumes previously split words by spaces and sentences by newlines.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (bool) output_with_sentence: set to True (default) to get the segmented sentence as part of the output on top of the dependencies. Set to False to keep dependencies only.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (bool) be_quiet: CoreNLPClient silent mode
:param (bool) chinese_only: set to True to ignore English and other languages. Set to False to process English and Chinese.
Stanford NLP dependencies manual:
https://nlp.stanford.edu/software/dependencies_manual.pdf
:return: Tuple of sentence, and dependency list nested in a list of sentences
if output_with_sentence==True:
[ (sentence,
[(dependency, source_word, target_word),(dependency, source_word, target_word)]
),
(sentence,
[(dependency, source_word, target_word),(dependency, source_word, target_word)]
),
...]
or Dependency string formatted as follows:
sentence
dependency(source,target), dependency(source,target), ....
sentence
dependency(source,target), dependency(source,target), ....
if output_with_sentence==False:
[ [(dependency, source_word, target_word),(dependency, source_word, target_word)],
[(dependency, source_word, target_word),(dependency, source_word, target_word)],
...]
or Dependency string formatted as follows:
dependency(source,target), dependency(source,target), ....
dependency(source,target), dependency(source,target), ....
Example:
en_text = 'This is a test sentence for the server to handle. I wonder what it will do.'
Dependency_Parse_str_langdetect(en_text, dependency_type='basicDependencies', sent_split=True, tolist=True, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False)
>>> [ (['This','is','a','test','sentence','for','the','server','to','handle','.'],
[('nsubj', 'sentence', 'This'),
('cop', 'sentence', 'is'),
('det', 'sentence', 'a'),
('compound', 'sentence', 'test'),
('acl', 'sentence', 'handle'),
('punct', 'sentence', '.'),
('det', 'server', 'the'),
('mark', 'handle', 'for'),
('nsubj', 'handle', 'server'),
('mark', 'handle', 'to')]
),
(['I', 'wonder', 'what', 'it', 'will', 'do', '.'],
[('obj', 'do', 'what'),
('nsubj', 'do', 'it'),
('aux', 'do', 'will'),
('ccomp', 'wonder', 'do'),
('punct', 'wonder', '.'),
('nsubj', 'wonder', 'I')]
)
]
print(Dependency_Parse_str_langdetect(en_text, dependency_type='basicDependencies', sent_split=True, tolist=False, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False))
>>>
This is a test sentence for the server to handle .
nsubj(sentence,This), cop(sentence,is), det(sentence,a), compound(sentence,test), acl(sentence,handle), punct(sentence,.), det(server,the), mark(handle,for), nsubj(handle,server), mark(handle,to)
I wonder what it will do .
obj(do,what), nsubj(do,it), aux(do,will), ccomp(wonder,do), punct(wonder,.), nsubj(wonder,I)
zh_text = "国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"
Dependency_Parse_str_langdetect(zh_text, dependency_type='basicDependencies', sent_split=True, tolist=True, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False)
>>>[( ['国务院','日前','发出','紧急','通知',',','要求','各','地','切实','落实','保证','市场','供应','的','各','项','政策',',','维护','副食品','价格','稳定','。'],
[('nsubj', '发出', '国务院'),
('nmod:tmod', '发出', '日前'),
('dobj', '发出', '通知'),
('punct', '发出', ','),
('conj', '发出', '要求'),
('punct', '发出', '。'),
('amod', '通知', '紧急'),
('dobj', '要求', '地'),
('ccomp', '要求', '落实'),
('det', '地', '各'),
('advmod', '落实', '切实'),
('ccomp', '落实', '保证'),
('dobj', '保证', '政策'),
('punct', '保证', ','),
('conj', '保证', '维护'),
('compound:nn', '供应', '市场'),
('case', '供应', '的'),
('mark:clf', '各', '项'),
('det', '政策', '各'),
('nmod:assmod', '政策', '供应'),
('dobj', '维护', '稳定'),
('compound:nn', '稳定', '副食品'),
('compound:nn', '稳定', '价格')]
)]
print(Dependency_Parse_str_langdetect(zh_text, dependency_type='basicDependencies', sent_split=True, tolist=False, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False))
>>>
国务院 日前 发出 紧急 通知 , 要求 各 地 切实 落实 保证 市场 供应 的 各 项 政策 , 维护 副食品 价格 稳定 。
nsubj(发出,国务院), nmod:tmod(发出,日前), dobj(发出,通知), punct(发出,,), conj(发出,要求), punct(发出,。), amod(通知,紧急), dobj(要求,地), ccomp(要求,落实), det(地,各), advmod(落实,切实), ccomp(落实,保证), dobj(保证,政策), punct(保证,,), conj(保证,维护), compound:nn(供应,市场), case(供应,的), mark:clf(各,项), det(政策,各), nmod:assmod(政策,供应), dobj(维护,稳定), compound:nn(稳定,副食品), compound:nn(稳定,价格)
'''
annotators=['depparse']
if pre_tokenized:
if not properties:
properties={'tokenize_pretokenized': True}
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
else:
properties.update({'tokenize_pretokenized': True})
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
if sent_split==False:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
if text!='':
if use_str_langdetect:
try:
lang = langdetect.detect(text)
except langdetect.lang_detect_exception.LangDetectException:
lang = "undetermined"
if chinese_only:
parse_ok = (lang == "zh-cn")
else:
parse_ok = (lang == "zh-cn") or (lang == "en")
else:
parse_ok = True
if no_str_langdetect_chinese:
lang = 'zh-cn'
if parse_ok:
if (lang == "zh-cn"):
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
ann = client.annotate(text)
#######
deps = []
if not tolist: deps_strs = []
for sent in ann.sentence:
words = dict([(i+1,token.word) for i,token in enumerate(sent.token)])
sentence_words = [token.word for token in sent.token]
if output_with_sentence:
deps_sent_str = ' '.join(sentence_words) + '\n'
else:
deps_sent_str = ''
if dependency_type == None: depTree = sent.basicDependencies
elif dependency_type == 'alternativeDependencies': depTree = sent.alternativeDependencies
elif dependency_type == 'basicDependencies': depTree = sent.basicDependencies
elif dependency_type == 'collapsedCCProcessedDependencies': depTree = sent.collapsedCCProcessedDependencies
elif dependency_type == 'collapsedDependencies': depTree = sent.collapsedDependencies
elif dependency_type == 'enhancedDependencies': depTree = sent.enhancedDependencies
elif dependency_type == 'enhancedPlusPlusDependencies': depTree = sent.enhancedPlusPlusDependencies
else: depTree = sent.basicDependencies
if output_with_sentence:
deps_sent = (sentence_words, [(edge.dep, words[edge.source], words[edge.target]) for edge in depTree.edge])
else:
deps_sent = [(edge.dep, words[edge.source], words[edge.target]) for edge in depTree.edge]
deps.append(deps_sent)
if not tolist:
if output_with_sentence:
deps_sent_str += ', '.join(['{}({},{})'.format(dep_tup[0],dep_tup[1],dep_tup[2]) for dep_tup in deps_sent[1]])
else:
deps_sent_str += ', '.join(['{}({},{})'.format(dep_tup[0],dep_tup[1],dep_tup[2]) for dep_tup in deps_sent])
deps_strs.append(deps_sent_str)
if not tolist:
if output_with_sentence:
deps_str = '\n\n'.join(deps_strs)
else:
deps_str = '\n'.join(deps_strs)
else:
deps = None
deps_str = ''
else:
deps = None
deps_str = ''
if tolist:
return deps
else:
return deps_str
def Dependency_Parse(text_list,
dependency_type='basicDependencies',
sent_split=False,
pre_tokenized=True,
tolist=True,
output_with_sentence=True,
properties=None,
timeout=15000,
verbose=1,
lang='zh-cn'):
'''
Processes a list of Chinese or English texts and collects the dependency, source word and target word in a list of tuples nested in a list of sentences, in a list of documents.
:param (list[str] | tuple[str] | str) text_list: list of strings of raw text for the CoreNLPServer to parse
:param (str) dependency_type: Choose from the options Stanford NLP has available. Default basicDependencies.
'alternativeDependencies'
'basicDependencies'
'collapsedCCProcessedDependencies'
'collapsedDependencies'
'enhancedDependencies'
'enhancedPlusPlusDependencies'
:param (bool) sent_split: Set True to split text into sentences. Set False to keep the text as one sentence.
:param (bool) pre_tokenized: Avoids loading the tokenizer if true. Assumes previously split words by spaces and sentences by newlines.
:param (bool) tolist: set to True (default) for a list of words nested in a list of sentences. Set False for a sentences split by newlines and words split by spaces.
:param (bool) output_with_sentence: set to True (default) to get the segmented sentence as part of the output on top of the dependencies. Set to False to keep dependencies only.
:param (dict) properties: additional request properties (written on top of Chinese ones exported here)
:param (int) timeout: CoreNLP server time before raising exception.
:param (int) verbose: verbose level
0: CoreNLPClient silent mode, no progress printing
1: CoreNLPClient silent mode, progress printing
2: CoreNLPClient silent mode off, no progress printing
3: CoreNLPClient silent mode off, progress printing
:param (str) lang: 'zh-cn' for Chinese and 'en' for English
Stanford NLP dependencies manual:
https://nlp.stanford.edu/software/dependencies_manual.pdf
Since updates, Stanford CoreNLP now uses Universal Dependencies.
Universal Dependencies website:
https://universaldependencies.org/#language-
:return: List per document of: Tuple of sentence, and dependency list nested in a list of sentences
if output_with_sentence==True:
[ [(sentence,
[(dependency, source_word, target_word),(dependency, source_word, target_word)]
),
(sentence,
[(dependency, source_word, target_word),(dependency, source_word, target_word)]
),
...], # per document
...]
or List per document of dependency string formatted as follows:
["sentence
dependency(source,target), dependency(source,target), ....
sentence
dependency(source,target), dependency(source,target), ....", #per sentence
...] # per document
if output_with_sentence==False:
[ [
[(dependency, source_word, target_word),(dependency, source_word, target_word)],
[(dependency, source_word, target_word),(dependency, source_word, target_word)],
...], # per document
...]
or List per document of dependency string formatted as follows:
[ "dependency(source,target), dependency(source,target), ....
dependency(source,target), dependency(source,target), ....", # per document
...]
Example:
en_texts = ['This is a test sentence for the server to handle. I wonder what it will do.']
Dependency_Parse(en_text, dependency_type='basicDependencies', sent_split=True, tolist=True, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False)
>>> [[ (['This','is','a','test','sentence','for','the','server','to','handle','.'],
[('nsubj', 'sentence', 'This'),
('cop', 'sentence', 'is'),
('det', 'sentence', 'a'),
('compound', 'sentence', 'test'),
('acl', 'sentence', 'handle'),
('punct', 'sentence', '.'),
('det', 'server', 'the'),
('mark', 'handle', 'for'),
('nsubj', 'handle', 'server'),
('mark', 'handle', 'to')]
),
(['I', 'wonder', 'what', 'it', 'will', 'do', '.'],
[('obj', 'do', 'what'),
('nsubj', 'do', 'it'),
('aux', 'do', 'will'),
('ccomp', 'wonder', 'do'),
('punct', 'wonder', '.'),
('nsubj', 'wonder', 'I')]
)
]]
Dependency_Parse(en_texts, dependency_type='basicDependencies', sent_split=True, tolist=False, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False))
>>>["This is a test sentence for the server to handle .
nsubj(sentence,This), cop(sentence,is), det(sentence,a), compound(sentence,test), acl(sentence,handle), punct(sentence,.), det(server,the), mark(handle,for), nsubj(handle,server), mark(handle,to)
I wonder what it will do .
obj(do,what), nsubj(do,it), aux(do,will), ccomp(wonder,do), punct(wonder,.), nsubj(wonder,I)"]
zh_texts = ["国务院日前发出紧急通知,要求各地切实落实保证市场供应的各项政策,维护副食品价格稳定。"]
Dependency_Parse(zh_texts, dependency_type='basicDependencies', sent_split=True, tolist=True, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False)
>>>[[( ['国务院','日前','发出','紧急','通知',',','要求','各','地','切实','落实','保证','市场','供应','的','各','项','政策',',','维护','副食品','价格','稳定','。'],
[('nsubj', '发出', '国务院'),
('nmod:tmod', '发出', '日前'),
('dobj', '发出', '通知'),
('punct', '发出', ','),
('conj', '发出', '要求'),
('punct', '发出', '。'),
('amod', '通知', '紧急'),
('dobj', '要求', '地'),
('ccomp', '要求', '落实'),
('det', '地', '各'),
('advmod', '落实', '切实'),
('ccomp', '落实', '保证'),
('dobj', '保证', '政策'),
('punct', '保证', ','),
('conj', '保证', '维护'),
('compound:nn', '供应', '市场'),
('case', '供应', '的'),
('mark:clf', '各', '项'),
('det', '政策', '各'),
('nmod:assmod', '政策', '供应'),
('dobj', '维护', '稳定'),
('compound:nn', '稳定', '副食品'),
('compound:nn', '稳定', '价格')]
)]]
Dependency_Parse(zh_texts, dependency_type='basicDependencies', sent_split=True, tolist=False, output_with_sentence=True, pre_tokenized=False, properties=None, timeout=15000, chinese_only=False))
>>>
["国务院 日前 发出 紧急 通知 , 要求 各 地 切实 落实 保证 市场 供应 的 各 项 政策 , 维护 副食品 价格 稳定 。
nsubj(发出,国务院), nmod:tmod(发出,日前), dobj(发出,通知), punct(发出,,), conj(发出,要求), punct(发出,。), amod(通知,紧急), dobj(要求,地), ccomp(要求,落实), det(地,各), advmod(落实,切实), ccomp(落实,保证), dobj(保证,政策), punct(保证,,), conj(保证,维护), compound:nn(供应,市场), case(供应,的), mark:clf(各,项), det(政策,各), nmod:assmod(政策,供应), dobj(维护,稳定), compound:nn(稳定,副食品), compound:nn(稳定,价格)"]
'''
if type(text_list)==type(''):
text_list = [text_list]
if pre_tokenized:
if not properties:
properties={'tokenize_pretokenized': True}
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
else:
properties.update({'tokenize_pretokenized': True})
# Assume the text is tokenized by white space and sentence split by newline. Do not run a model.
if sent_split==False:
if not properties:
properties={'tokenize_no_ssplit':True}
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
else:
properties.update({'tokenize_no_ssplit':True})
# Assume the sentences are split by two continuous newlines (\n\n). Only run tokenization and disable sentence segmentation.
if lang == "zh-cn":
properties = get_StanfordCoreNLP_chinese_properties(properties=properties)
annotators=['depparse']
if verbose == 0:
be_quiet = True
print_progress = False
elif verbose == 1:
be_quiet = True
print_progress = True
elif verbose == 2:
be_quiet = False
print_progress = False
elif verbose == 3:
be_quiet = False
print_progress = True
else:
be_quiet = False
print_progress = True
result = []
limit = len(text_list)
with CoreNLPClient(annotators=annotators, properties=properties, timeout=timeout, be_quiet=be_quiet) as client:
for i ,text in enumerate(text_list):
if print_progress:
if lang=='zh-cn':
print("Dependency Parsing Chinese sentence {} of {}".format(i+1,limit))
elif lang=='en':
print("Dependency Parsing English sentence {} of {}".format(i+1,limit))
if text!='':
ann = client.annotate(text)
#######
deps = []
if not tolist: deps_strs = []
for sent in ann.sentence:
words = dict([(i+1,token.word) for i,token in enumerate(sent.token)])
sentence_words = [token.word for token in sent.token]
if output_with_sentence:
deps_sent_str = ' '.join(sentence_words) + '\n'
else:
deps_sent_str = ''
if dependency_type == None: depTree = sent.basicDependencies
elif dependency_type == 'alternativeDependencies': depTree = sent.alternativeDependencies
elif dependency_type == 'basicDependencies': depTree = sent.basicDependencies
elif dependency_type == 'collapsedCCProcessedDependencies': depTree = sent.collapsedCCProcessedDependencies
elif dependency_type == 'collapsedDependencies': depTree = sent.collapsedDependencies
elif dependency_type == 'enhancedDependencies': depTree = sent.enhancedDependencies
elif dependency_type == 'enhancedPlusPlusDependencies': depTree = sent.enhancedPlusPlusDependencies
else: depTree = sent.basicDependencies
if output_with_sentence:
deps_sent = (sentence_words, [(edge.dep, words[edge.source], words[edge.target]) for edge in depTree.edge])
else:
deps_sent = [(edge.dep, words[edge.source], words[edge.target]) for edge in depTree.edge]
deps.append(deps_sent)
if not tolist:
if output_with_sentence:
deps_sent_str += ', '.join(['{}({},{})'.format(dep_tup[0],dep_tup[1],dep_tup[2]) for dep_tup in deps_sent[1]])
else:
deps_sent_str += ', '.join(['{}({},{})'.format(dep_tup[0],dep_tup[1],dep_tup[2]) for dep_tup in deps_sent])
deps_strs.append(deps_sent_str)
if not tolist:
if output_with_sentence:
deps_str = '\n\n'.join(deps_strs)
else:
deps_str = '\n'.join(deps_strs)