nltk 3.2__zip → 3.3__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (406) hide show
  1. {nltk-3.2 → nltk-3.3}/INSTALL.txt +6 -6
  2. {nltk-3.2 → nltk-3.3}/LICENSE.txt +13 -13
  3. {nltk-3.2 → nltk-3.3}/MANIFEST.in +6 -6
  4. {nltk-3.2/nltk.egg-info → nltk-3.3}/PKG-INFO +13 -5
  5. nltk-3.2/README.txt → nltk-3.3/README.md +49 -48
  6. nltk-3.3/nltk/VERSION +1 -0
  7. {nltk-3.2 → nltk-3.3}/nltk/__init__.py +185 -185
  8. {nltk-3.2 → nltk-3.3}/nltk/app/__init__.py +52 -53
  9. {nltk-3.2 → nltk-3.3}/nltk/app/chartparser_app.py +2276 -2276
  10. {nltk-3.2 → nltk-3.3}/nltk/app/chunkparser_app.py +1262 -1264
  11. {nltk-3.2 → nltk-3.3}/nltk/app/collocations_app.py +347 -350
  12. {nltk-3.2 → nltk-3.3}/nltk/app/concordance_app.py +568 -570
  13. {nltk-3.2 → nltk-3.3}/nltk/app/nemo_app.py +156 -155
  14. {nltk-3.2 → nltk-3.3}/nltk/app/rdparser_app.py +892 -894
  15. {nltk-3.2 → nltk-3.3}/nltk/app/srparser_app.py +809 -809
  16. {nltk-3.2 → nltk-3.3}/nltk/app/wordfreq_app.py +32 -32
  17. {nltk-3.2 → nltk-3.3}/nltk/app/wordnet_app.py +968 -968
  18. {nltk-3.2 → nltk-3.3}/nltk/book.py +91 -90
  19. {nltk-3.2 → nltk-3.3}/nltk/ccg/__init__.py +22 -22
  20. {nltk-3.2 → nltk-3.3}/nltk/ccg/api.py +359 -335
  21. {nltk-3.2 → nltk-3.3}/nltk/ccg/chart.py +394 -361
  22. {nltk-3.2 → nltk-3.3}/nltk/ccg/combinator.py +343 -312
  23. {nltk-3.2 → nltk-3.3}/nltk/ccg/lexicon.py +328 -290
  24. nltk-3.3/nltk/ccg/logic.py +46 -0
  25. {nltk-3.2 → nltk-3.3}/nltk/chat/__init__.py +49 -49
  26. {nltk-3.2 → nltk-3.3}/nltk/chat/eliza.py +244 -244
  27. {nltk-3.2 → nltk-3.3}/nltk/chat/iesha.py +140 -140
  28. {nltk-3.2 → nltk-3.3}/nltk/chat/rude.py +92 -92
  29. {nltk-3.2 → nltk-3.3}/nltk/chat/suntsu.py +117 -117
  30. {nltk-3.2 → nltk-3.3}/nltk/chat/util.py +122 -120
  31. {nltk-3.2 → nltk-3.3}/nltk/chat/zen.py +282 -282
  32. {nltk-3.2 → nltk-3.3}/nltk/chunk/__init__.py +190 -190
  33. {nltk-3.2 → nltk-3.3}/nltk/chunk/api.py +51 -51
  34. {nltk-3.2 → nltk-3.3}/nltk/chunk/named_entity.py +331 -331
  35. {nltk-3.2 → nltk-3.3}/nltk/chunk/regexp.py +1390 -1384
  36. {nltk-3.2 → nltk-3.3}/nltk/chunk/util.py +600 -600
  37. {nltk-3.2 → nltk-3.3}/nltk/classify/__init__.py +98 -98
  38. {nltk-3.2 → nltk-3.3}/nltk/classify/api.py +193 -193
  39. {nltk-3.2 → nltk-3.3}/nltk/classify/decisiontree.py +295 -295
  40. {nltk-3.2 → nltk-3.3}/nltk/classify/maxent.py +1510 -1492
  41. {nltk-3.2 → nltk-3.3}/nltk/classify/megam.py +179 -178
  42. {nltk-3.2 → nltk-3.3}/nltk/classify/naivebayes.py +245 -242
  43. {nltk-3.2 → nltk-3.3}/nltk/classify/positivenaivebayes.py +170 -170
  44. {nltk-3.2 → nltk-3.3}/nltk/classify/rte_classify.py +160 -191
  45. {nltk-3.2 → nltk-3.3}/nltk/classify/scikitlearn.py +153 -151
  46. {nltk-3.2 → nltk-3.3}/nltk/classify/senna.py +183 -181
  47. {nltk-3.2 → nltk-3.3}/nltk/classify/svm.py +15 -15
  48. {nltk-3.2 → nltk-3.3}/nltk/classify/tadm.py +113 -112
  49. {nltk-3.2 → nltk-3.3}/nltk/classify/textcat.py +193 -193
  50. {nltk-3.2 → nltk-3.3}/nltk/classify/util.py +324 -312
  51. {nltk-3.2 → nltk-3.3}/nltk/classify/weka.py +346 -345
  52. {nltk-3.2 → nltk-3.3}/nltk/cluster/__init__.py +86 -86
  53. {nltk-3.2 → nltk-3.3}/nltk/cluster/api.py +74 -70
  54. {nltk-3.2 → nltk-3.3}/nltk/cluster/em.py +247 -247
  55. {nltk-3.2 → nltk-3.3}/nltk/cluster/gaac.py +168 -168
  56. {nltk-3.2 → nltk-3.3}/nltk/cluster/kmeans.py +221 -221
  57. {nltk-3.2 → nltk-3.3}/nltk/cluster/util.py +304 -289
  58. nltk-3.3/nltk/collections.py +640 -0
  59. {nltk-3.2 → nltk-3.3}/nltk/collocations.py +388 -388
  60. nltk-3.3/nltk/compat.py +365 -0
  61. {nltk-3.2 → nltk-3.3}/nltk/corpus/__init__.py +341 -320
  62. {nltk-3.2 → nltk-3.3}/nltk/corpus/europarl_raw.py +44 -44
  63. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/__init__.py +147 -145
  64. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/aligned.py +115 -114
  65. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/api.py +448 -446
  66. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/bnc.py +252 -252
  67. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/bracket_parse.py +227 -227
  68. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/categorized_sents.py +179 -178
  69. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/chasen.py +140 -139
  70. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/childes.py +522 -494
  71. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/chunked.py +212 -212
  72. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/cmudict.py +97 -95
  73. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/comparative_sents.py +280 -278
  74. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/conll.py +528 -521
  75. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/crubadan.py +116 -116
  76. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/dependency.py +101 -101
  77. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/framenet.py +3059 -2093
  78. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ieer.py +112 -111
  79. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/indian.py +85 -86
  80. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ipipan.py +332 -331
  81. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/knbc.py +187 -187
  82. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/lin.py +156 -156
  83. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/mte.py +311 -310
  84. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nkjp.py +429 -428
  85. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nombank.py +421 -421
  86. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nps_chat.py +73 -73
  87. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/opinion_lexicon.py +115 -115
  88. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/panlex_lite.py +165 -165
  89. nltk-3.3/nltk/corpus/reader/pl196x.py +292 -0
  90. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/plaintext.py +232 -233
  91. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ppattach.py +96 -95
  92. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/propbank.py +479 -481
  93. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/pros_cons.py +128 -126
  94. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/reviews.py +330 -328
  95. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/rte.py +144 -146
  96. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/semcor.py +256 -256
  97. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/senseval.py +203 -201
  98. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/sentiwordnet.py +137 -137
  99. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/sinica_treebank.py +75 -75
  100. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/string_category.py +60 -59
  101. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/switchboard.py +119 -119
  102. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/tagged.py +295 -294
  103. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/timit.py +452 -450
  104. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/toolbox.py +68 -68
  105. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/twitter.py +155 -157
  106. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/udhr.py +80 -80
  107. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/util.py +804 -800
  108. nltk-3.3/nltk/corpus/reader/verbnet.py +595 -0
  109. nltk-3.3/nltk/corpus/reader/wordlist.py +134 -0
  110. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/wordnet.py +2108 -2036
  111. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/xmldocs.py +392 -387
  112. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ycoe.py +243 -242
  113. {nltk-3.2 → nltk-3.3}/nltk/corpus/util.py +144 -127
  114. {nltk-3.2 → nltk-3.3}/nltk/data.py +1487 -1451
  115. {nltk-3.2 → nltk-3.3}/nltk/decorators.py +219 -215
  116. {nltk-3.2 → nltk-3.3}/nltk/downloader.py +2278 -2274
  117. {nltk-3.2 → nltk-3.3}/nltk/draw/__init__.py +27 -27
  118. {nltk-3.2 → nltk-3.3}/nltk/draw/cfg.py +774 -777
  119. {nltk-3.2 → nltk-3.3}/nltk/draw/dispersion.py +58 -58
  120. {nltk-3.2 → nltk-3.3}/nltk/draw/table.py +1098 -1098
  121. {nltk-3.2 → nltk-3.3}/nltk/draw/tree.py +963 -966
  122. {nltk-3.2 → nltk-3.3}/nltk/draw/util.py +2356 -2356
  123. {nltk-3.2 → nltk-3.3}/nltk/featstruct.py +2617 -2500
  124. {nltk-3.2 → nltk-3.3}/nltk/grammar.py +1559 -1516
  125. {nltk-3.2 → nltk-3.3}/nltk/help.py +56 -56
  126. {nltk-3.2 → nltk-3.3}/nltk/inference/__init__.py +20 -20
  127. {nltk-3.2 → nltk-3.3}/nltk/inference/api.py +597 -589
  128. {nltk-3.2 → nltk-3.3}/nltk/inference/discourse.py +612 -608
  129. {nltk-3.2 → nltk-3.3}/nltk/inference/mace.py +311 -311
  130. {nltk-3.2 → nltk-3.3}/nltk/inference/nonmonotonic.py +509 -509
  131. {nltk-3.2 → nltk-3.3}/nltk/inference/prover9.py +431 -431
  132. {nltk-3.2 → nltk-3.3}/nltk/inference/resolution.py +687 -687
  133. {nltk-3.2 → nltk-3.3}/nltk/inference/tableau.py +607 -607
  134. {nltk-3.2 → nltk-3.3}/nltk/internals.py +982 -982
  135. {nltk-3.2 → nltk-3.3}/nltk/jsontags.py +63 -63
  136. {nltk-3.2 → nltk-3.3}/nltk/lazyimport.py +142 -142
  137. {nltk-3.2 → nltk-3.3}/nltk/metrics/__init__.py +30 -29
  138. {nltk-3.2 → nltk-3.3}/nltk/metrics/agreement.py +421 -401
  139. nltk-3.3/nltk/metrics/aline.py +607 -0
  140. {nltk-3.2 → nltk-3.3}/nltk/metrics/association.py +414 -410
  141. {nltk-3.2 → nltk-3.3}/nltk/metrics/confusionmatrix.py +206 -206
  142. {nltk-3.2 → nltk-3.3}/nltk/metrics/distance.py +207 -202
  143. {nltk-3.2 → nltk-3.3}/nltk/metrics/paice.py +381 -381
  144. {nltk-3.2 → nltk-3.3}/nltk/metrics/scores.py +228 -228
  145. {nltk-3.2 → nltk-3.3}/nltk/metrics/segmentation.py +231 -232
  146. {nltk-3.2 → nltk-3.3}/nltk/metrics/spearman.py +69 -69
  147. {nltk-3.2 → nltk-3.3}/nltk/misc/__init__.py +11 -11
  148. {nltk-3.2 → nltk-3.3}/nltk/misc/babelfish.py +10 -10
  149. {nltk-3.2 → nltk-3.3}/nltk/misc/chomsky.py +135 -133
  150. {nltk-3.2 → nltk-3.3}/nltk/misc/minimalset.py +83 -83
  151. {nltk-3.2 → nltk-3.3}/nltk/misc/sort.py +157 -157
  152. {nltk-3.2 → nltk-3.3}/nltk/misc/wordfinder.py +129 -129
  153. {nltk-3.2 → nltk-3.3}/nltk/parse/__init__.py +81 -80
  154. {nltk-3.2 → nltk-3.3}/nltk/parse/api.py +66 -66
  155. {nltk-3.2 → nltk-3.3}/nltk/parse/bllip.py +282 -282
  156. {nltk-3.2 → nltk-3.3}/nltk/parse/chart.py +1682 -1681
  157. nltk-3.3/nltk/parse/corenlp.py +780 -0
  158. {nltk-3.2 → nltk-3.3}/nltk/parse/dependencygraph.py +760 -758
  159. {nltk-3.2 → nltk-3.3}/nltk/parse/earleychart.py +452 -451
  160. {nltk-3.2 → nltk-3.3}/nltk/parse/evaluate.py +129 -129
  161. {nltk-3.2 → nltk-3.3}/nltk/parse/featurechart.py +580 -578
  162. {nltk-3.2 → nltk-3.3}/nltk/parse/generate.py +87 -76
  163. {nltk-3.2 → nltk-3.3}/nltk/parse/malt.py +356 -356
  164. {nltk-3.2 → nltk-3.3}/nltk/parse/nonprojectivedependencyparser.py +783 -783
  165. {nltk-3.2 → nltk-3.3}/nltk/parse/pchart.py +522 -522
  166. {nltk-3.2 → nltk-3.3}/nltk/parse/projectivedependencyparser.py +579 -578
  167. {nltk-3.2 → nltk-3.3}/nltk/parse/recursivedescent.py +655 -656
  168. {nltk-3.2 → nltk-3.3}/nltk/parse/shiftreduce.py +458 -459
  169. {nltk-3.2 → nltk-3.3}/nltk/parse/stanford.py +431 -406
  170. {nltk-3.2 → nltk-3.3}/nltk/parse/transitionparser.py +774 -772
  171. {nltk-3.2 → nltk-3.3}/nltk/parse/util.py +231 -231
  172. {nltk-3.2 → nltk-3.3}/nltk/parse/viterbi.py +401 -401
  173. {nltk-3.2 → nltk-3.3}/nltk/probability.py +2410 -2355
  174. {nltk-3.2 → nltk-3.3}/nltk/sem/__init__.py +61 -61
  175. {nltk-3.2 → nltk-3.3}/nltk/sem/boxer.py +1261 -1261
  176. {nltk-3.2 → nltk-3.3}/nltk/sem/chat80.py +782 -782
  177. {nltk-3.2 → nltk-3.3}/nltk/sem/cooper_storage.py +118 -118
  178. {nltk-3.2 → nltk-3.3}/nltk/sem/drt.py +1258 -1257
  179. {nltk-3.2 → nltk-3.3}/nltk/sem/drt_glue_demo.py +485 -489
  180. {nltk-3.2 → nltk-3.3}/nltk/sem/evaluate.py +790 -784
  181. {nltk-3.2 → nltk-3.3}/nltk/sem/glue.py +696 -694
  182. {nltk-3.2 → nltk-3.3}/nltk/sem/hole.py +386 -384
  183. {nltk-3.2 → nltk-3.3}/nltk/sem/lfg.py +210 -208
  184. {nltk-3.2 → nltk-3.3}/nltk/sem/linearlogic.py +451 -449
  185. {nltk-3.2 → nltk-3.3}/nltk/sem/logic.py +1910 -1910
  186. {nltk-3.2 → nltk-3.3}/nltk/sem/relextract.py +476 -483
  187. {nltk-3.2 → nltk-3.3}/nltk/sem/skolemize.py +101 -101
  188. {nltk-3.2 → nltk-3.3}/nltk/sem/util.py +249 -249
  189. {nltk-3.2 → nltk-3.3}/nltk/sentiment/__init__.py +14 -14
  190. {nltk-3.2 → nltk-3.3}/nltk/sentiment/sentiment_analyzer.py +229 -229
  191. {nltk-3.2 → nltk-3.3}/nltk/sentiment/util.py +762 -752
  192. {nltk-3.2 → nltk-3.3}/nltk/sentiment/vader.py +443 -445
  193. {nltk-3.2 → nltk-3.3}/nltk/stem/__init__.py +31 -33
  194. {nltk-3.2 → nltk-3.3}/nltk/stem/api.py +28 -25
  195. nltk-3.3/nltk/stem/arlstem.py +369 -0
  196. {nltk-3.2 → nltk-3.3}/nltk/stem/isri.py +345 -345
  197. {nltk-3.2 → nltk-3.3}/nltk/stem/lancaster.py +337 -310
  198. nltk-3.3/nltk/stem/porter.py +710 -0
  199. {nltk-3.2 → nltk-3.3}/nltk/stem/regexp.py +61 -61
  200. {nltk-3.2 → nltk-3.3}/nltk/stem/rslp.py +142 -142
  201. {nltk-3.2 → nltk-3.3}/nltk/stem/snowball.py +4236 -3712
  202. {nltk-3.2 → nltk-3.3}/nltk/stem/util.py +22 -12
  203. {nltk-3.2 → nltk-3.3}/nltk/stem/wordnet.py +51 -51
  204. {nltk-3.2 → nltk-3.3}/nltk/tag/__init__.py +152 -127
  205. {nltk-3.2 → nltk-3.3}/nltk/tag/api.py +86 -81
  206. {nltk-3.2 → nltk-3.3}/nltk/tag/brill.py +424 -426
  207. {nltk-3.2 → nltk-3.3}/nltk/tag/brill_trainer.py +608 -608
  208. {nltk-3.2 → nltk-3.3}/nltk/tag/crf.py +204 -200
  209. {nltk-3.2 → nltk-3.3}/nltk/tag/hmm.py +1277 -1277
  210. {nltk-3.2 → nltk-3.3}/nltk/tag/hunpos.py +132 -132
  211. {nltk-3.2 → nltk-3.3}/nltk/tag/mapping.py +101 -101
  212. {nltk-3.2 → nltk-3.3}/nltk/tag/perceptron.py +329 -314
  213. {nltk-3.2 → nltk-3.3}/nltk/tag/senna.py +147 -145
  214. {nltk-3.2 → nltk-3.3}/nltk/tag/sequential.py +740 -736
  215. {nltk-3.2 → nltk-3.3}/nltk/tag/stanford.py +219 -196
  216. {nltk-3.2 → nltk-3.3}/nltk/tag/tnt.py +595 -604
  217. {nltk-3.2 → nltk-3.3}/nltk/tag/util.py +72 -72
  218. {nltk-3.2 → nltk-3.3}/nltk/tbl/__init__.py +28 -28
  219. {nltk-3.2 → nltk-3.3}/nltk/tbl/api.py +1 -1
  220. {nltk-3.2 → nltk-3.3}/nltk/tbl/demo.py +366 -366
  221. {nltk-3.2 → nltk-3.3}/nltk/tbl/erroranalysis.py +39 -39
  222. {nltk-3.2 → nltk-3.3}/nltk/tbl/feature.py +259 -261
  223. {nltk-3.2 → nltk-3.3}/nltk/tbl/rule.py +321 -321
  224. {nltk-3.2 → nltk-3.3}/nltk/tbl/template.py +303 -308
  225. {nltk-3.2 → nltk-3.3}/nltk/test/__init__.py +18 -18
  226. {nltk-3.2 → nltk-3.3}/nltk/test/all.py +24 -23
  227. {nltk-3.2 → nltk-3.3}/nltk/test/bleu.doctest +14 -14
  228. {nltk-3.2 → nltk-3.3}/nltk/test/bnc.doctest +60 -60
  229. {nltk-3.2 → nltk-3.3}/nltk/test/ccg.doctest +376 -395
  230. nltk-3.3/nltk/test/ccg_semantics.doctest +553 -0
  231. {nltk-3.2 → nltk-3.3}/nltk/test/chat80.doctest +234 -234
  232. {nltk-3.2 → nltk-3.3}/nltk/test/childes.doctest +184 -184
  233. {nltk-3.2 → nltk-3.3}/nltk/test/childes_fixt.py +14 -13
  234. {nltk-3.2 → nltk-3.3}/nltk/test/chunk.doctest +373 -373
  235. {nltk-3.2 → nltk-3.3}/nltk/test/classify.doctest +185 -185
  236. {nltk-3.2 → nltk-3.3}/nltk/test/classify_fixt.py +11 -10
  237. nltk-3.3/nltk/test/collections.doctest +20 -0
  238. {nltk-3.2 → nltk-3.3}/nltk/test/collocations.doctest +276 -276
  239. {nltk-3.2 → nltk-3.3}/nltk/test/compat.doctest +134 -138
  240. {nltk-3.2 → nltk-3.3}/nltk/test/compat_fixt.py +9 -8
  241. nltk-3.3/nltk/test/concordance.doctest +55 -0
  242. {nltk-3.2 → nltk-3.3}/nltk/test/corpus.doctest +2200 -2212
  243. {nltk-3.2 → nltk-3.3}/nltk/test/corpus_fixt.py +3 -3
  244. {nltk-3.2 → nltk-3.3}/nltk/test/crubadan.doctest +65 -65
  245. {nltk-3.2 → nltk-3.3}/nltk/test/data.doctest +379 -379
  246. {nltk-3.2 → nltk-3.3}/nltk/test/dependency.doctest +241 -241
  247. {nltk-3.2 → nltk-3.3}/nltk/test/discourse.doctest +546 -546
  248. {nltk-3.2 → nltk-3.3}/nltk/test/discourse_fixt.py +14 -13
  249. {nltk-3.2 → nltk-3.3}/nltk/test/doctest_nose_plugin.py +159 -156
  250. {nltk-3.2 → nltk-3.3}/nltk/test/drt.doctest +517 -517
  251. {nltk-3.2 → nltk-3.3}/nltk/test/featgram.doctest +607 -607
  252. {nltk-3.2 → nltk-3.3}/nltk/test/featstruct.doctest +1229 -1230
  253. {nltk-3.2 → nltk-3.3}/nltk/test/framenet.doctest +288 -239
  254. {nltk-3.2 → nltk-3.3}/nltk/test/generate.doctest +67 -67
  255. {nltk-3.2 → nltk-3.3}/nltk/test/gensim.doctest +140 -141
  256. {nltk-3.2 → nltk-3.3}/nltk/test/gensim_fixt.py +10 -9
  257. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics.doctest +384 -386
  258. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics_malt.doctest +68 -68
  259. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics_malt_fixt.py +12 -11
  260. {nltk-3.2 → nltk-3.3}/nltk/test/grammar.doctest +48 -48
  261. {nltk-3.2 → nltk-3.3}/nltk/test/grammartestsuites.doctest +109 -109
  262. {nltk-3.2 → nltk-3.3}/nltk/test/index.doctest +100 -100
  263. {nltk-3.2 → nltk-3.3}/nltk/test/inference.doctest +534 -534
  264. {nltk-3.2 → nltk-3.3}/nltk/test/inference_fixt.py +12 -11
  265. {nltk-3.2 → nltk-3.3}/nltk/test/internals.doctest +140 -140
  266. {nltk-3.2 → nltk-3.3}/nltk/test/japanese.doctest +48 -48
  267. {nltk-3.2 → nltk-3.3}/nltk/test/logic.doctest +1098 -1098
  268. {nltk-3.2 → nltk-3.3}/nltk/test/metrics.doctest +270 -270
  269. {nltk-3.2 → nltk-3.3}/nltk/test/misc.doctest +118 -118
  270. {nltk-3.2 → nltk-3.3}/nltk/test/nonmonotonic.doctest +286 -286
  271. {nltk-3.2 → nltk-3.3}/nltk/test/nonmonotonic_fixt.py +12 -11
  272. {nltk-3.2 → nltk-3.3}/nltk/test/paice.doctest +35 -35
  273. {nltk-3.2 → nltk-3.3}/nltk/test/parse.doctest +884 -884
  274. {nltk-3.2 → nltk-3.3}/nltk/test/portuguese_en.doctest +565 -565
  275. {nltk-3.2 → nltk-3.3}/nltk/test/portuguese_en_fixt.py +16 -16
  276. {nltk-3.2 → nltk-3.3}/nltk/test/probability.doctest +304 -304
  277. {nltk-3.2 → nltk-3.3}/nltk/test/probability_fixt.py +13 -12
  278. {nltk-3.2 → nltk-3.3}/nltk/test/propbank.doctest +176 -176
  279. {nltk-3.2 → nltk-3.3}/nltk/test/relextract.doctest +263 -263
  280. {nltk-3.2 → nltk-3.3}/nltk/test/resolution.doctest +221 -221
  281. {nltk-3.2 → nltk-3.3}/nltk/test/runtests.py +86 -64
  282. {nltk-3.2 → nltk-3.3}/nltk/test/segmentation_fixt.py +10 -10
  283. {nltk-3.2 → nltk-3.3}/nltk/test/semantics.doctest +665 -665
  284. {nltk-3.2 → nltk-3.3}/nltk/test/semantics_fixt.py +7 -7
  285. {nltk-3.2 → nltk-3.3}/nltk/test/sentiment.doctest +233 -233
  286. {nltk-3.2 → nltk-3.3}/nltk/test/sentiwordnet.doctest +41 -41
  287. {nltk-3.2 → nltk-3.3}/nltk/test/simple.doctest +85 -85
  288. {nltk-3.2 → nltk-3.3}/nltk/test/stem.doctest +78 -78
  289. {nltk-3.2 → nltk-3.3}/nltk/test/tag.doctest +33 -33
  290. {nltk-3.2 → nltk-3.3}/nltk/test/tokenize.doctest +273 -166
  291. {nltk-3.2 → nltk-3.3}/nltk/test/toolbox.doctest +307 -307
  292. {nltk-3.2 → nltk-3.3}/nltk/test/translate.doctest +242 -242
  293. {nltk-3.2 → nltk-3.3}/nltk/test/translate_fixt.py +3 -3
  294. {nltk-3.2 → nltk-3.3}/nltk/test/tree.doctest +1101 -1101
  295. {nltk-3.2 → nltk-3.3}/nltk/test/treeprettyprinter.doctest +127 -127
  296. {nltk-3.2 → nltk-3.3}/nltk/test/treetransforms.doctest +156 -156
  297. nltk-3.3/nltk/test/unit/test_2x_compat.py +63 -0
  298. nltk-3.3/nltk/test/unit/test_aline.py +52 -0
  299. nltk-3.3/nltk/test/unit/test_chunk.py +56 -0
  300. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_classify.py +55 -53
  301. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_collocations.py +88 -79
  302. nltk-3.3/nltk/test/unit/test_concordance.py +98 -0
  303. nltk-3.3/nltk/test/unit/test_corenlp.py +1000 -0
  304. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_corpora.py +200 -183
  305. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_corpus_views.py +45 -45
  306. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_hmm.py +88 -88
  307. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_json2csv_corpus.py +188 -187
  308. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_naivebayes.py +26 -26
  309. nltk-3.3/nltk/test/unit/test_rte_classify.py +86 -0
  310. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_seekable_unicode_stream_reader.py +124 -124
  311. nltk-3.3/nltk/test/unit/test_senna.py +74 -0
  312. nltk-3.3/nltk/test/unit/test_stem.py +121 -0
  313. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_tag.py +20 -20
  314. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_tgrep.py +628 -626
  315. nltk-3.3/nltk/test/unit/test_tokenize.py +168 -0
  316. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_twitter_auth.py +185 -185
  317. nltk-3.3/nltk/test/unit/test_wordnet.py +134 -0
  318. nltk-3.3/nltk/test/unit/translate/test_bleu.py +244 -0
  319. nltk-3.3/nltk/test/unit/translate/test_gdfa.py +57 -0
  320. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm1.py +75 -75
  321. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm2.py +87 -87
  322. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm3.py +105 -105
  323. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm4.py +126 -126
  324. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm5.py +166 -166
  325. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm_model.py +270 -270
  326. nltk-3.3/nltk/test/unit/translate/test_nist.py +37 -0
  327. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_stack_decoder.py +300 -300
  328. {nltk-3.2 → nltk-3.3}/nltk/test/unit/utils.py +41 -41
  329. {nltk-3.2 → nltk-3.3}/nltk/test/util.doctest +48 -48
  330. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet.doctest +595 -581
  331. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet_fixt.py +7 -6
  332. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet_lch.doctest +53 -53
  333. {nltk-3.2 → nltk-3.3}/nltk/test/wsd.doctest +68 -68
  334. {nltk-3.2 → nltk-3.3}/nltk/text.py +663 -610
  335. {nltk-3.2 → nltk-3.3}/nltk/tgrep.py +938 -937
  336. {nltk-3.2 → nltk-3.3}/nltk/tokenize/__init__.py +130 -107
  337. {nltk-3.2 → nltk-3.3}/nltk/tokenize/api.py +77 -78
  338. {nltk-3.2 → nltk-3.3}/nltk/tokenize/casual.py +343 -342
  339. {nltk-3.2 → nltk-3.3}/nltk/tokenize/mwe.py +120 -120
  340. nltk-3.3/nltk/tokenize/nist.py +173 -0
  341. {nltk-3.2 → nltk-3.3}/nltk/tokenize/punkt.py +1620 -1601
  342. {nltk-3.2 → nltk-3.3}/nltk/tokenize/regexp.py +208 -202
  343. nltk-3.3/nltk/tokenize/repp.py +151 -0
  344. {nltk-3.2 → nltk-3.3}/nltk/tokenize/sexpr.py +140 -142
  345. {nltk-3.2 → nltk-3.3}/nltk/tokenize/simple.py +138 -136
  346. {nltk-3.2 → nltk-3.3}/nltk/tokenize/stanford.py +117 -113
  347. nltk-3.3/nltk/tokenize/stanford_segmenter.py +246 -0
  348. {nltk-3.2 → nltk-3.3}/nltk/tokenize/texttiling.py +458 -460
  349. nltk-3.3/nltk/tokenize/toktok.py +155 -0
  350. nltk-3.3/nltk/tokenize/treebank.py +363 -0
  351. nltk-3.3/nltk/tokenize/util.py +261 -0
  352. {nltk-3.2 → nltk-3.3}/nltk/toolbox.py +499 -497
  353. {nltk-3.2 → nltk-3.3}/nltk/translate/__init__.py +24 -24
  354. {nltk-3.2 → nltk-3.3}/nltk/translate/api.py +331 -321
  355. {nltk-3.2 → nltk-3.3}/nltk/translate/bleu_score.py +615 -556
  356. nltk-3.3/nltk/translate/chrf_score.py +137 -0
  357. {nltk-3.2 → nltk-3.3}/nltk/translate/gale_church.py +248 -235
  358. {nltk-3.2 → nltk-3.3}/nltk/translate/gdfa.py +135 -131
  359. nltk-3.3/nltk/translate/gleu_score.py +193 -0
  360. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm1.py +250 -241
  361. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm2.py +308 -308
  362. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm3.py +337 -337
  363. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm4.py +467 -467
  364. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm5.py +639 -639
  365. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm_model.py +536 -533
  366. {nltk-3.2 → nltk-3.3}/nltk/translate/metrics.py +40 -40
  367. nltk-3.3/nltk/translate/nist_score.py +178 -0
  368. {nltk-3.2 → nltk-3.3}/nltk/translate/phrase_based.py +175 -175
  369. {nltk-3.2 → nltk-3.3}/nltk/translate/ribes_score.py +325 -325
  370. {nltk-3.2 → nltk-3.3}/nltk/translate/stack_decoder.py +499 -495
  371. {nltk-3.2 → nltk-3.3}/nltk/tree.py +1605 -1603
  372. {nltk-3.2 → nltk-3.3}/nltk/treeprettyprinter.py +564 -564
  373. {nltk-3.2 → nltk-3.3}/nltk/treetransforms.py +309 -309
  374. {nltk-3.2 → nltk-3.3}/nltk/twitter/__init__.py +28 -28
  375. {nltk-3.2 → nltk-3.3}/nltk/twitter/api.py +141 -136
  376. {nltk-3.2 → nltk-3.3}/nltk/twitter/common.py +264 -258
  377. {nltk-3.2 → nltk-3.3}/nltk/twitter/twitter_demo.py +288 -288
  378. {nltk-3.2 → nltk-3.3}/nltk/twitter/twitterclient.py +530 -530
  379. {nltk-3.2 → nltk-3.3}/nltk/twitter/util.py +147 -146
  380. nltk-3.3/nltk/util.py +751 -0
  381. {nltk-3.2 → nltk-3.3}/nltk/wsd.py +53 -53
  382. {nltk-3.2 → nltk-3.3/nltk.egg-info}/PKG-INFO +13 -5
  383. {nltk-3.2 → nltk-3.3}/nltk.egg-info/SOURCES.txt +26 -3
  384. nltk-3.3/nltk.egg-info/requires.txt +31 -0
  385. {nltk-3.2 → nltk-3.3}/setup.cfg +0 -1
  386. {nltk-3.2 → nltk-3.3}/setup.py +102 -75
  387. nltk-3.2/nltk/VERSION +0 -1
  388. nltk-3.2/nltk/compat.py +0 -680
  389. nltk-3.2/nltk/corpus/reader/pl196x.py +0 -278
  390. nltk-3.2/nltk/corpus/reader/verbnet.py +0 -408
  391. nltk-3.2/nltk/corpus/reader/wordlist.py +0 -37
  392. nltk-3.2/nltk/sentiment/vader_lexicon.txt +0 -7517
  393. nltk-3.2/nltk/six.py +0 -868
  394. nltk-3.2/nltk/stem/porter.py +0 -692
  395. nltk-3.2/nltk/test/unit/test_2x_compat.py +0 -26
  396. nltk-3.2/nltk/test/unit/test_stem.py +0 -36
  397. nltk-3.2/nltk/test/unit/test_tokenize.py +0 -23
  398. nltk-3.2/nltk/test/unit/translate/test_bleu.py +0 -84
  399. nltk-3.2/nltk/tokenize/treebank.py +0 -124
  400. nltk-3.2/nltk/tokenize/util.py +0 -90
  401. nltk-3.2/nltk/util.py +0 -1364
  402. {nltk-3.2 → nltk-3.3}/nltk/test/unit/__init__.py +0 -0
  403. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/__init__.py +0 -0
  404. {nltk-3.2 → nltk-3.3}/nltk.egg-info/dependency_links.txt +0 -0
  405. {nltk-3.2 → nltk-3.3}/nltk.egg-info/not-zip-safe +0 -0
  406. {nltk-3.2 → nltk-3.3}/nltk.egg-info/top_level.txt +0 -0
@@ -1,982 +1,982 @@
1
- # Natural Language Toolkit: Internal utility functions
2
- #
3
- # Copyright (C) 2001-2015 NLTK Project
4
- # Author: Steven Bird <stevenbird1@gmail.com>
5
- # Edward Loper <edloper@gmail.com>
6
- # Nitin Madnani <nmadnani@ets.org>
7
- # URL: <http://nltk.org/>
8
- # For license information, see LICENSE.TXT
9
- from __future__ import print_function
10
-
11
- import subprocess
12
- import os
13
- import fnmatch
14
- import re
15
- import warnings
16
- import textwrap
17
- import types
18
- import sys
19
- import stat
20
- import locale
21
-
22
- # Use the c version of ElementTree, which is faster, if possible:
23
- try:
24
- from xml.etree import cElementTree as ElementTree
25
- except ImportError:
26
- from xml.etree import ElementTree
27
-
28
- from nltk import __file__
29
- from nltk import compat
30
-
31
- ##########################################################################
32
- # Java Via Command-Line
33
- ##########################################################################
34
-
35
- _java_bin = None
36
- _java_options = []
37
- # [xx] add classpath option to config_java?
38
- def config_java(bin=None, options=None, verbose=True):
39
- """
40
- Configure nltk's java interface, by letting nltk know where it can
41
- find the Java binary, and what extra options (if any) should be
42
- passed to Java when it is run.
43
-
44
- :param bin: The full path to the Java binary. If not specified,
45
- then nltk will search the system for a Java binary; and if
46
- one is not found, it will raise a ``LookupError`` exception.
47
- :type bin: str
48
- :param options: A list of options that should be passed to the
49
- Java binary when it is called. A common value is
50
- ``'-Xmx512m'``, which tells Java binary to increase
51
- the maximum heap size to 512 megabytes. If no options are
52
- specified, then do not modify the options list.
53
- :type options: list(str)
54
- """
55
- global _java_bin, _java_options
56
- _java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe'])
57
-
58
- if options is not None:
59
- if isinstance(options, compat.string_types):
60
- options = options.split()
61
- _java_options = list(options)
62
-
63
- def java(cmd, classpath=None, stdin=None, stdout=None, stderr=None,
64
- blocking=True):
65
- """
66
- Execute the given java command, by opening a subprocess that calls
67
- Java. If java has not yet been configured, it will be configured
68
- by calling ``config_java()`` with no arguments.
69
-
70
- :param cmd: The java command that should be called, formatted as
71
- a list of strings. Typically, the first string will be the name
72
- of the java class; and the remaining strings will be arguments
73
- for that java class.
74
- :type cmd: list(str)
75
-
76
- :param classpath: A ``':'`` separated list of directories, JAR
77
- archives, and ZIP archives to search for class files.
78
- :type classpath: str
79
-
80
- :param stdin, stdout, stderr: Specify the executed programs'
81
- standard input, standard output and standard error file
82
- handles, respectively. Valid values are ``subprocess.PIPE``,
83
- an existing file descriptor (a positive integer), an existing
84
- file object, and None. ``subprocess.PIPE`` indicates that a
85
- new pipe to the child should be created. With None, no
86
- redirection will occur; the child's file handles will be
87
- inherited from the parent. Additionally, stderr can be
88
- ``subprocess.STDOUT``, which indicates that the stderr data
89
- from the applications should be captured into the same file
90
- handle as for stdout.
91
-
92
- :param blocking: If ``false``, then return immediately after
93
- spawning the subprocess. In this case, the return value is
94
- the ``Popen`` object, and not a ``(stdout, stderr)`` tuple.
95
-
96
- :return: If ``blocking=True``, then return a tuple ``(stdout,
97
- stderr)``, containing the stdout and stderr outputs generated
98
- by the java command if the ``stdout`` and ``stderr`` parameters
99
- were set to ``subprocess.PIPE``; or None otherwise. If
100
- ``blocking=False``, then return a ``subprocess.Popen`` object.
101
-
102
- :raise OSError: If the java command returns a nonzero return code.
103
- """
104
- if stdin == 'pipe': stdin = subprocess.PIPE
105
- if stdout == 'pipe': stdout = subprocess.PIPE
106
- if stderr == 'pipe': stderr = subprocess.PIPE
107
- if isinstance(cmd, compat.string_types):
108
- raise TypeError('cmd should be a list of strings')
109
-
110
- # Make sure we know where a java binary is.
111
- if _java_bin is None:
112
- config_java()
113
-
114
- # Set up the classpath.
115
- if isinstance(classpath, compat.string_types):
116
- classpaths=[classpath]
117
- else:
118
- classpaths=list(classpath)
119
- classpath=os.path.pathsep.join(classpaths)
120
-
121
- # Construct the full command string.
122
- cmd = list(cmd)
123
- cmd = ['-cp', classpath] + cmd
124
- cmd = [_java_bin] + _java_options + cmd
125
-
126
- # Call java via a subprocess
127
- p = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr)
128
- if not blocking: return p
129
- (stdout, stderr) = p.communicate()
130
-
131
- # Check the return code.
132
- if p.returncode != 0:
133
- print(_decode_stdoutdata(stderr))
134
- raise OSError('Java command failed : ' + str(cmd))
135
-
136
- return (stdout, stderr)
137
-
138
- if 0:
139
- #config_java(options='-Xmx512m')
140
- # Write:
141
- #java('weka.classifiers.bayes.NaiveBayes',
142
- # ['-d', '/tmp/names.model', '-t', '/tmp/train.arff'],
143
- # classpath='/Users/edloper/Desktop/weka/weka.jar')
144
- # Read:
145
- (a,b) = java(['weka.classifiers.bayes.NaiveBayes',
146
- '-l', '/tmp/names.model', '-T', '/tmp/test.arff',
147
- '-p', '0'],#, '-distribution'],
148
- classpath='/Users/edloper/Desktop/weka/weka.jar')
149
-
150
-
151
- ######################################################################
152
- # Parsing
153
- ######################################################################
154
-
155
- class ReadError(ValueError):
156
- """
157
- Exception raised by read_* functions when they fail.
158
- :param position: The index in the input string where an error occurred.
159
- :param expected: What was expected when an error occurred.
160
- """
161
- def __init__(self, expected, position):
162
- ValueError.__init__(self, expected, position)
163
- self.expected = expected
164
- self.position = position
165
- def __str__(self):
166
- return 'Expected %s at %s' % (self.expected, self.position)
167
-
168
- _STRING_START_RE = re.compile(r"[uU]?[rR]?(\"\"\"|\'\'\'|\"|\')")
169
- def read_str(s, start_position):
170
- """
171
- If a Python string literal begins at the specified position in the
172
- given string, then return a tuple ``(val, end_position)``
173
- containing the value of the string literal and the position where
174
- it ends. Otherwise, raise a ``ReadError``.
175
-
176
- :param s: A string that will be checked to see if within which a
177
- Python string literal exists.
178
- :type s: str
179
-
180
- :param start_position: The specified beginning position of the string ``s``
181
- to begin regex matching.
182
- :type start_position: int
183
-
184
- :return: A tuple containing the matched string literal evaluated as a
185
- string and the end position of the string literal.
186
- :rtype: tuple(str, int)
187
-
188
- :raise ReadError: If the ``_STRING_START_RE`` regex doesn't return a
189
- match in ``s`` at ``start_position``, i.e., open quote. If the
190
- ``_STRING_END_RE`` regex doesn't return a match in ``s`` at the
191
- end of the first match, i.e., close quote.
192
- :raise ValueError: If an invalid string (i.e., contains an invalid
193
- escape sequence) is passed into the ``eval``.
194
-
195
- :Example:
196
- >>> from nltk.internals import read_str
197
- >>> read_str('"Hello", World!', 0)
198
- ('Hello', 7)
199
-
200
- """
201
- # Read the open quote, and any modifiers.
202
- m = _STRING_START_RE.match(s, start_position)
203
- if not m: raise ReadError('open quote', start_position)
204
- quotemark = m.group(1)
205
-
206
- # Find the close quote.
207
- _STRING_END_RE = re.compile(r'\\|%s' % quotemark)
208
- position = m.end()
209
- while True:
210
- match = _STRING_END_RE.search(s, position)
211
- if not match: raise ReadError('close quote', position)
212
- if match.group(0) == '\\': position = match.end()+1
213
- else: break
214
-
215
- # Process it, using eval. Strings with invalid escape sequences
216
- # might raise ValueEerror.
217
- try:
218
- return eval(s[start_position:match.end()]), match.end()
219
- except ValueError as e:
220
- raise ReadError('invalid string (%s)' % e)
221
-
222
- _READ_INT_RE = re.compile(r'-?\d+')
223
- def read_int(s, start_position):
224
- """
225
- If an integer begins at the specified position in the given
226
- string, then return a tuple ``(val, end_position)`` containing the
227
- value of the integer and the position where it ends. Otherwise,
228
- raise a ``ReadError``.
229
-
230
- :param s: A string that will be checked to see if within which a
231
- Python integer exists.
232
- :type s: str
233
-
234
- :param start_position: The specified beginning position of the string ``s``
235
- to begin regex matching.
236
- :type start_position: int
237
-
238
- :return: A tuple containing the matched integer casted to an int,
239
- and the end position of the int in ``s``.
240
- :rtype: tuple(int, int)
241
-
242
- :raise ReadError: If the ``_READ_INT_RE`` regex doesn't return a
243
- match in ``s`` at ``start_position``.
244
-
245
- :Example:
246
- >>> from nltk.internals import read_int
247
- >>> read_int('42 is the answer', 0)
248
- (42, 2)
249
-
250
- """
251
- m = _READ_INT_RE.match(s, start_position)
252
- if not m: raise ReadError('integer', start_position)
253
- return int(m.group()), m.end()
254
-
255
- _READ_NUMBER_VALUE = re.compile(r'-?(\d*)([.]?\d*)?')
256
- def read_number(s, start_position):
257
- """
258
- If an integer or float begins at the specified position in the
259
- given string, then return a tuple ``(val, end_position)``
260
- containing the value of the number and the position where it ends.
261
- Otherwise, raise a ``ReadError``.
262
-
263
- :param s: A string that will be checked to see if within which a
264
- Python number exists.
265
- :type s: str
266
-
267
- :param start_position: The specified beginning position of the string ``s``
268
- to begin regex matching.
269
- :type start_position: int
270
-
271
- :return: A tuple containing the matched number casted to a ``float``,
272
- and the end position of the number in ``s``.
273
- :rtype: tuple(float, int)
274
-
275
- :raise ReadError: If the ``_READ_NUMBER_VALUE`` regex doesn't return a
276
- match in ``s`` at ``start_position``.
277
-
278
- :Example:
279
- >>> from nltk.internals import read_number
280
- >>> read_number('Pi is 3.14159', 6)
281
- (3.14159, 13)
282
-
283
- """
284
- m = _READ_NUMBER_VALUE.match(s, start_position)
285
- if not m or not (m.group(1) or m.group(2)):
286
- raise ReadError('number', start_position)
287
- if m.group(2): return float(m.group()), m.end()
288
- else: return int(m.group()), m.end()
289
-
290
-
291
-
292
- ######################################################################
293
- # Check if a method has been overridden
294
- ######################################################################
295
-
296
- def overridden(method):
297
- """
298
- :return: True if ``method`` overrides some method with the same
299
- name in a base class. This is typically used when defining
300
- abstract base classes or interfaces, to allow subclasses to define
301
- either of two related methods:
302
-
303
- >>> class EaterI:
304
- ... '''Subclass must define eat() or batch_eat().'''
305
- ... def eat(self, food):
306
- ... if overridden(self.batch_eat):
307
- ... return self.batch_eat([food])[0]
308
- ... else:
309
- ... raise NotImplementedError()
310
- ... def batch_eat(self, foods):
311
- ... return [self.eat(food) for food in foods]
312
-
313
- :type method: instance method
314
- """
315
- # [xx] breaks on classic classes!
316
- if isinstance(method, types.MethodType) and compat.get_im_class(method) is not None:
317
- name = method.__name__
318
- funcs = [cls.__dict__[name]
319
- for cls in _mro(compat.get_im_class(method))
320
- if name in cls.__dict__]
321
- return len(funcs) > 1
322
- else:
323
- raise TypeError('Expected an instance method.')
324
-
325
- def _mro(cls):
326
- """
327
- Return the method resolution order for ``cls`` -- i.e., a list
328
- containing ``cls`` and all its base classes, in the order in which
329
- they would be checked by ``getattr``. For new-style classes, this
330
- is just cls.__mro__. For classic classes, this can be obtained by
331
- a depth-first left-to-right traversal of ``__bases__``.
332
- """
333
- if isinstance(cls, type):
334
- return cls.__mro__
335
- else:
336
- mro = [cls]
337
- for base in cls.__bases__: mro.extend(_mro(base))
338
- return mro
339
-
340
- ######################################################################
341
- # Deprecation decorator & base class
342
- ######################################################################
343
- # [xx] dedent msg first if it comes from a docstring.
344
-
345
- def _add_epytext_field(obj, field, message):
346
- """Add an epytext @field to a given object's docstring."""
347
- indent = ''
348
- # If we already have a docstring, then add a blank line to separate
349
- # it from the new field, and check its indentation.
350
- if obj.__doc__:
351
- obj.__doc__ = obj.__doc__.rstrip()+'\n\n'
352
- indents = re.findall(r'(?<=\n)[ ]+(?!\s)', obj.__doc__.expandtabs())
353
- if indents: indent = min(indents)
354
- # If we don't have a docstring, add an empty one.
355
- else:
356
- obj.__doc__ = ''
357
-
358
- obj.__doc__ += textwrap.fill('@%s: %s' % (field, message),
359
- initial_indent=indent,
360
- subsequent_indent=indent+' ')
361
-
362
- def deprecated(message):
363
- """
364
- A decorator used to mark functions as deprecated. This will cause
365
- a warning to be printed the when the function is used. Usage:
366
-
367
- >>> from nltk.internals import deprecated
368
- >>> @deprecated('Use foo() instead')
369
- ... def bar(x):
370
- ... print(x/10)
371
-
372
- """
373
-
374
- def decorator(func):
375
- msg = ("Function %s() has been deprecated. %s"
376
- % (func.__name__, message))
377
- msg = '\n' + textwrap.fill(msg, initial_indent=' ',
378
- subsequent_indent=' ')
379
- def newFunc(*args, **kwargs):
380
- warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
381
- return func(*args, **kwargs)
382
-
383
- # Copy the old function's name, docstring, & dict
384
- newFunc.__dict__.update(func.__dict__)
385
- newFunc.__name__ = func.__name__
386
- newFunc.__doc__ = func.__doc__
387
- newFunc.__deprecated__ = True
388
- # Add a @deprecated field to the docstring.
389
- _add_epytext_field(newFunc, 'deprecated', message)
390
- return newFunc
391
- return decorator
392
-
393
- class Deprecated(object):
394
- """
395
- A base class used to mark deprecated classes. A typical usage is to
396
- alert users that the name of a class has changed:
397
-
398
- >>> from nltk.internals import Deprecated
399
- >>> class NewClassName(object):
400
- ... pass # All logic goes here.
401
- ...
402
- >>> class OldClassName(Deprecated, NewClassName):
403
- ... "Use NewClassName instead."
404
-
405
- The docstring of the deprecated class will be used in the
406
- deprecation warning message.
407
- """
408
- def __new__(cls, *args, **kwargs):
409
- # Figure out which class is the deprecated one.
410
- dep_cls = None
411
- for base in _mro(cls):
412
- if Deprecated in base.__bases__:
413
- dep_cls = base; break
414
- assert dep_cls, 'Unable to determine which base is deprecated.'
415
-
416
- # Construct an appropriate warning.
417
- doc = dep_cls.__doc__ or ''.strip()
418
- # If there's a @deprecated field, strip off the field marker.
419
- doc = re.sub(r'\A\s*@deprecated:', r'', doc)
420
- # Strip off any indentation.
421
- doc = re.sub(r'(?m)^\s*', '', doc)
422
- # Construct a 'name' string.
423
- name = 'Class %s' % dep_cls.__name__
424
- if cls != dep_cls:
425
- name += ' (base class for %s)' % cls.__name__
426
- # Put it all together.
427
- msg = '%s has been deprecated. %s' % (name, doc)
428
- # Wrap it.
429
- msg = '\n' + textwrap.fill(msg, initial_indent=' ',
430
- subsequent_indent=' ')
431
- warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
432
- # Do the actual work of __new__.
433
- return object.__new__(cls)
434
-
435
- ##########################################################################
436
- # COUNTER, FOR UNIQUE NAMING
437
- ##########################################################################
438
-
439
- class Counter:
440
- """
441
- A counter that auto-increments each time its value is read.
442
- """
443
- def __init__(self, initial_value=0):
444
- self._value = initial_value
445
- def get(self):
446
- self._value += 1
447
- return self._value
448
-
449
- ##########################################################################
450
- # Search for files/binaries
451
- ##########################################################################
452
-
453
- def find_file_iter(filename, env_vars=(), searchpath=(),
454
- file_names=None, url=None, verbose=True, finding_dir=False):
455
- """
456
- Search for a file to be used by nltk.
457
-
458
- :param filename: The name or path of the file.
459
- :param env_vars: A list of environment variable names to check.
460
- :param file_names: A list of alternative file names to check.
461
- :param searchpath: List of directories to search.
462
- :param url: URL presented to user for download help.
463
- :param verbose: Whether or not to print path when a file is found.
464
- """
465
- file_names = [filename] + (file_names or [])
466
- assert isinstance(filename, compat.string_types)
467
- assert not isinstance(file_names, compat.string_types)
468
- assert not isinstance(searchpath, compat.string_types)
469
- if isinstance(env_vars, compat.string_types):
470
- env_vars = env_vars.split()
471
- yielded = False
472
-
473
- # File exists, no magic
474
- for alternative in file_names:
475
- path_to_file = os.path.join(filename, alternative)
476
- if os.path.isfile(path_to_file):
477
- if verbose:
478
- print('[Found %s: %s]' % (filename, path_to_file))
479
- yielded = True
480
- yield path_to_file
481
- # Check the bare alternatives
482
- if os.path.isfile(alternative):
483
- if verbose:
484
- print('[Found %s: %s]' % (filename, alternative))
485
- yielded = True
486
- yield alternative
487
- # Check if the alternative is inside a 'file' directory
488
- path_to_file = os.path.join(filename, 'file', alternative)
489
- if os.path.isfile(path_to_file):
490
- if verbose:
491
- print('[Found %s: %s]' % (filename, path_to_file))
492
- yielded = True
493
- yield path_to_file
494
-
495
- # Check environment variables
496
- for env_var in env_vars:
497
- if env_var in os.environ:
498
- if finding_dir: # This is to file a directory instead of file
499
- yielded = True
500
- yield os.environ[env_var]
501
-
502
- for env_dir in os.environ[env_var].split(os.pathsep):
503
- # Check if the environment variable contains a direct path to the bin
504
- if os.path.isfile(env_dir):
505
- if verbose:
506
- print('[Found %s: %s]'%(filename, env_dir))
507
- yielded = True
508
- yield env_dir
509
- # Check if the possible bin names exist inside the environment variable directories
510
- for alternative in file_names:
511
- path_to_file = os.path.join(env_dir, alternative)
512
- if os.path.isfile(path_to_file):
513
- if verbose:
514
- print('[Found %s: %s]'%(filename, path_to_file))
515
- yielded = True
516
- yield path_to_file
517
- # Check if the alternative is inside a 'file' directory
518
- # path_to_file = os.path.join(env_dir, 'file', alternative)
519
-
520
- # Check if the alternative is inside a 'bin' directory
521
- path_to_file = os.path.join(env_dir, 'bin', alternative)
522
-
523
- if os.path.isfile(path_to_file):
524
- if verbose:
525
- print('[Found %s: %s]' % (filename, path_to_file))
526
- yielded = True
527
- yield path_to_file
528
-
529
- # Check the path list.
530
- for directory in searchpath:
531
- for alternative in file_names:
532
- path_to_file = os.path.join(directory, alternative)
533
- if os.path.isfile(path_to_file):
534
- yielded = True
535
- yield path_to_file
536
-
537
- # If we're on a POSIX system, then try using the 'which' command
538
- # to find the file.
539
- if os.name == 'posix':
540
- for alternative in file_names:
541
- try:
542
- p = subprocess.Popen(['which', alternative],
543
- stdout=subprocess.PIPE, stderr=subprocess.PIPE)
544
- stdout, stderr = p.communicate()
545
- path = _decode_stdoutdata(stdout).strip()
546
- if path.endswith(alternative) and os.path.exists(path):
547
- if verbose:
548
- print('[Found %s: %s]' % (filename, path))
549
- yielded = True
550
- yield path
551
- except (KeyboardInterrupt, SystemExit, OSError):
552
- raise
553
- except:
554
- pass
555
-
556
- if not yielded:
557
- msg = ("NLTK was unable to find the %s file!" "\nUse software specific "
558
- "configuration paramaters" % filename)
559
- if env_vars: msg += ' or set the %s environment variable' % env_vars[0]
560
- msg += '.'
561
- if searchpath:
562
- msg += '\n\n Searched in:'
563
- msg += ''.join('\n - %s' % d for d in searchpath)
564
- if url: msg += ('\n\n For more information on %s, see:\n <%s>' %
565
- (filename, url))
566
- div = '='*75
567
- raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
568
-
569
-
570
- def find_file(filename, env_vars=(), searchpath=(),
571
- file_names=None, url=None, verbose=True):
572
- return next(find_file_iter(filename, env_vars, searchpath,
573
- file_names, url, verbose))
574
-
575
-
576
- def find_dir(filename, env_vars=(), searchpath=(),
577
- file_names=None, url=None, verbose=True):
578
- return next(find_file_iter(filename, env_vars, searchpath,
579
- file_names, url, verbose, finding_dir=True))
580
-
581
-
582
- def find_binary_iter(name, path_to_bin=None, env_vars=(), searchpath=(),
583
- binary_names=None, url=None, verbose=True):
584
- """
585
- Search for a file to be used by nltk.
586
-
587
- :param name: The name or path of the file.
588
- :param path_to_bin: The user-supplied binary location (deprecated)
589
- :param env_vars: A list of environment variable names to check.
590
- :param file_names: A list of alternative file names to check.
591
- :param searchpath: List of directories to search.
592
- :param url: URL presented to user for download help.
593
- :param verbose: Whether or not to print path when a file is found.
594
- """
595
- for file in find_file_iter(path_to_bin or name, env_vars, searchpath, binary_names,
596
- url, verbose):
597
- yield file
598
-
599
- def find_binary(name, path_to_bin=None, env_vars=(), searchpath=(),
600
- binary_names=None, url=None, verbose=True):
601
- return next(find_binary_iter(name, path_to_bin, env_vars, searchpath,
602
- binary_names, url, verbose))
603
-
604
- def find_jar_iter(name_pattern, path_to_jar=None, env_vars=(),
605
- searchpath=(), url=None, verbose=True, is_regex=False):
606
- """
607
- Search for a jar that is used by nltk.
608
-
609
- :param name_pattern: The name of the jar file
610
- :param path_to_jar: The user-supplied jar location, or None.
611
- :param env_vars: A list of environment variable names to check
612
- in addition to the CLASSPATH variable which is
613
- checked by default.
614
- :param searchpath: List of directories to search.
615
- :param is_regex: Whether name is a regular expression.
616
- """
617
-
618
- assert isinstance(name_pattern, compat.string_types)
619
- assert not isinstance(searchpath, compat.string_types)
620
- if isinstance(env_vars, compat.string_types):
621
- env_vars = env_vars.split()
622
- yielded = False
623
-
624
- # Make sure we check the CLASSPATH first
625
- env_vars = ['CLASSPATH'] + list(env_vars)
626
-
627
- # If an explicit location was given, then check it, and yield it if
628
- # it's present; otherwise, complain.
629
- if path_to_jar is not None:
630
- if os.path.isfile(path_to_jar):
631
- yielded = True
632
- yield path_to_jar
633
- else:
634
- raise LookupError('Could not find %s jar file at %s' %
635
- (name_pattern, path_to_jar))
636
-
637
- # Check environment variables
638
- for env_var in env_vars:
639
- if env_var in os.environ:
640
- if env_var == 'CLASSPATH':
641
- classpath = os.environ['CLASSPATH']
642
- for cp in classpath.split(os.path.pathsep):
643
- if os.path.isfile(cp):
644
- filename=os.path.basename(cp)
645
- if is_regex and re.match(name_pattern, filename) or \
646
- (not is_regex and filename == name_pattern):
647
- if verbose:
648
- print('[Found %s: %s]' % (name_pattern, cp))
649
- yielded = True
650
- yield cp
651
- # The case where user put directory containing the jar file in the classpath
652
- if os.path.isdir(cp):
653
- if not is_regex:
654
- if os.path.isfile(os.path.join(cp,name_pattern)):
655
- if verbose:
656
- print('[Found %s: %s]' % (name_pattern, cp))
657
- yielded = True
658
- yield os.path.join(cp,name_pattern)
659
- else:
660
- # Look for file using regular expression
661
- for file_name in os.listdir(cp):
662
- if re.match(name_pattern,file_name):
663
- if verbose:
664
- print('[Found %s: %s]' % (name_pattern, os.path.join(cp,file_name)))
665
- yielded = True
666
- yield os.path.join(cp,file_name)
667
-
668
- else:
669
- jar_env = os.environ[env_var]
670
- jar_iter = ((os.path.join(jar_env, path_to_jar) for path_to_jar in os.listdir(jar_env))
671
- if os.path.isdir(jar_env) else (jar_env,))
672
- for path_to_jar in jar_iter:
673
- if os.path.isfile(path_to_jar):
674
- filename=os.path.basename(path_to_jar)
675
- if is_regex and re.match(name_pattern, filename) or \
676
- (not is_regex and filename == name_pattern):
677
- if verbose:
678
- print('[Found %s: %s]' % (name_pattern, path_to_jar))
679
- yielded = True
680
- yield path_to_jar
681
-
682
- # Check the path list.
683
- for directory in searchpath:
684
- if is_regex:
685
- for filename in os.listdir(directory):
686
- path_to_jar = os.path.join(directory, filename)
687
- if os.path.isfile(path_to_jar):
688
- if re.match(name_pattern, filename):
689
- if verbose:
690
- print('[Found %s: %s]' % (filename, path_to_jar))
691
- yielded = True
692
- yield path_to_jar
693
- else:
694
- path_to_jar = os.path.join(directory, name_pattern)
695
- if os.path.isfile(path_to_jar):
696
- if verbose:
697
- print('[Found %s: %s]' % (name_pattern, path_to_jar))
698
- yielded = True
699
- yield path_to_jar
700
-
701
- if not yielded:
702
- # If nothing was found, raise an error
703
- msg = ("NLTK was unable to find %s!" % name_pattern)
704
- if env_vars: msg += ' Set the %s environment variable' % env_vars[0]
705
- msg = textwrap.fill(msg+'.', initial_indent=' ',
706
- subsequent_indent=' ')
707
- if searchpath:
708
- msg += '\n\n Searched in:'
709
- msg += ''.join('\n - %s' % d for d in searchpath)
710
- if url:
711
- msg += ('\n\n For more information, on %s, see:\n <%s>' %
712
- (name_pattern, url))
713
- div = '='*75
714
- raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
715
-
716
- def find_jar(name_pattern, path_to_jar=None, env_vars=(),
717
- searchpath=(), url=None, verbose=True, is_regex=False):
718
- return next(find_jar_iter(name_pattern, path_to_jar, env_vars,
719
- searchpath, url, verbose, is_regex))
720
-
721
-
722
- def find_jars_within_path(path_to_jars):
723
- return [os.path.join(root, filename)
724
- for root, dirnames, filenames in os.walk(path_to_jars)
725
- for filename in fnmatch.filter(filenames, '*.jar')]
726
-
727
- def _decode_stdoutdata(stdoutdata):
728
- """ Convert data read from stdout/stderr to unicode """
729
- if not isinstance(stdoutdata, bytes):
730
- return stdoutdata
731
-
732
- encoding = getattr(sys.__stdout__, "encoding", locale.getpreferredencoding())
733
- if encoding is None:
734
- return stdoutdata.decode()
735
- return stdoutdata.decode(encoding)
736
-
737
- ##########################################################################
738
- # Import Stdlib Module
739
- ##########################################################################
740
-
741
- def import_from_stdlib(module):
742
- """
743
- When python is run from within the nltk/ directory tree, the
744
- current directory is included at the beginning of the search path.
745
- Unfortunately, that means that modules within nltk can sometimes
746
- shadow standard library modules. As an example, the stdlib
747
- 'inspect' module will attempt to import the stdlib 'tokenize'
748
- module, but will instead end up importing NLTK's 'tokenize' module
749
- instead (causing the import to fail).
750
- """
751
- old_path = sys.path
752
- sys.path = [d for d in sys.path if d not in ('', '.')]
753
- m = __import__(module)
754
- sys.path = old_path
755
- return m
756
-
757
-
758
- ##########################################################################
759
- # Wrapper for ElementTree Elements
760
- ##########################################################################
761
-
762
- @compat.python_2_unicode_compatible
763
- class ElementWrapper(object):
764
- """
765
- A wrapper around ElementTree Element objects whose main purpose is
766
- to provide nicer __repr__ and __str__ methods. In addition, any
767
- of the wrapped Element's methods that return other Element objects
768
- are overridden to wrap those values before returning them.
769
-
770
- This makes Elements more convenient to work with in
771
- interactive sessions and doctests, at the expense of some
772
- efficiency.
773
- """
774
-
775
- # Prevent double-wrapping:
776
- def __new__(cls, etree):
777
- """
778
- Create and return a wrapper around a given Element object.
779
- If ``etree`` is an ``ElementWrapper``, then ``etree`` is
780
- returned as-is.
781
- """
782
- if isinstance(etree, ElementWrapper):
783
- return etree
784
- else:
785
- return object.__new__(ElementWrapper)
786
-
787
- def __init__(self, etree):
788
- r"""
789
- Initialize a new Element wrapper for ``etree``.
790
-
791
- If ``etree`` is a string, then it will be converted to an
792
- Element object using ``ElementTree.fromstring()`` first:
793
-
794
- >>> ElementWrapper("<test></test>")
795
- <Element "<?xml version='1.0' encoding='utf8'?>\n<test />">
796
-
797
- """
798
- if isinstance(etree, compat.string_types):
799
- etree = ElementTree.fromstring(etree)
800
- self.__dict__['_etree'] = etree
801
-
802
- def unwrap(self):
803
- """
804
- Return the Element object wrapped by this wrapper.
805
- """
806
- return self._etree
807
-
808
- ##////////////////////////////////////////////////////////////
809
- #{ String Representation
810
- ##////////////////////////////////////////////////////////////
811
-
812
- def __repr__(self):
813
- s = ElementTree.tostring(self._etree, encoding='utf8').decode('utf8')
814
- if len(s) > 60:
815
- e = s.rfind('<')
816
- if (len(s)-e) > 30: e = -20
817
- s = '%s...%s' % (s[:30], s[e:])
818
- return '<Element %r>' % s
819
-
820
- def __str__(self):
821
- """
822
- :return: the result of applying ``ElementTree.tostring()`` to
823
- the wrapped Element object.
824
- """
825
- return ElementTree.tostring(self._etree, encoding='utf8').decode('utf8').rstrip()
826
-
827
- ##////////////////////////////////////////////////////////////
828
- #{ Element interface Delegation (pass-through)
829
- ##////////////////////////////////////////////////////////////
830
-
831
- def __getattr__(self, attrib):
832
- return getattr(self._etree, attrib)
833
-
834
- def __setattr__(self, attr, value):
835
- return setattr(self._etree, attr, value)
836
-
837
- def __delattr__(self, attr):
838
- return delattr(self._etree, attr)
839
-
840
- def __setitem__(self, index, element):
841
- self._etree[index] = element
842
-
843
- def __delitem__(self, index):
844
- del self._etree[index]
845
-
846
- def __setslice__(self, start, stop, elements):
847
- self._etree[start:stop] = elements
848
-
849
- def __delslice__(self, start, stop):
850
- del self._etree[start:stop]
851
-
852
- def __len__(self):
853
- return len(self._etree)
854
-
855
- ##////////////////////////////////////////////////////////////
856
- #{ Element interface Delegation (wrap result)
857
- ##////////////////////////////////////////////////////////////
858
-
859
- def __getitem__(self, index):
860
- return ElementWrapper(self._etree[index])
861
-
862
- def __getslice__(self, start, stop):
863
- return [ElementWrapper(elt) for elt in self._etree[start:stop]]
864
-
865
- def getchildren(self):
866
- return [ElementWrapper(elt) for elt in self._etree]
867
-
868
- def getiterator(self, tag=None):
869
- return (ElementWrapper(elt)
870
- for elt in self._etree.getiterator(tag))
871
-
872
- def makeelement(self, tag, attrib):
873
- return ElementWrapper(self._etree.makeelement(tag, attrib))
874
-
875
- def find(self, path):
876
- elt = self._etree.find(path)
877
- if elt is None: return elt
878
- else: return ElementWrapper(elt)
879
-
880
- def findall(self, path):
881
- return [ElementWrapper(elt) for elt in self._etree.findall(path)]
882
-
883
- ######################################################################
884
- # Helper for Handling Slicing
885
- ######################################################################
886
-
887
- def slice_bounds(sequence, slice_obj, allow_step=False):
888
- """
889
- Given a slice, return the corresponding (start, stop) bounds,
890
- taking into account None indices and negative indices. The
891
- following guarantees are made for the returned start and stop values:
892
-
893
- - 0 <= start <= len(sequence)
894
- - 0 <= stop <= len(sequence)
895
- - start <= stop
896
-
897
- :raise ValueError: If ``slice_obj.step`` is not None.
898
- :param allow_step: If true, then the slice object may have a
899
- non-None step. If it does, then return a tuple
900
- (start, stop, step).
901
- """
902
- start, stop = (slice_obj.start, slice_obj.stop)
903
-
904
- # If allow_step is true, then include the step in our return
905
- # value tuple.
906
- if allow_step:
907
- step = slice_obj.step
908
- if step is None: step = 1
909
- # Use a recursive call without allow_step to find the slice
910
- # bounds. If step is negative, then the roles of start and
911
- # stop (in terms of default values, etc), are swapped.
912
- if step < 0:
913
- start, stop = slice_bounds(sequence, slice(stop, start))
914
- else:
915
- start, stop = slice_bounds(sequence, slice(start, stop))
916
- return start, stop, step
917
-
918
- # Otherwise, make sure that no non-default step value is used.
919
- elif slice_obj.step not in (None, 1):
920
- raise ValueError('slices with steps are not supported by %s' %
921
- sequence.__class__.__name__)
922
-
923
- # Supply default offsets.
924
- if start is None: start = 0
925
- if stop is None: stop = len(sequence)
926
-
927
- # Handle negative indices.
928
- if start < 0: start = max(0, len(sequence)+start)
929
- if stop < 0: stop = max(0, len(sequence)+stop)
930
-
931
- # Make sure stop doesn't go past the end of the list. Note that
932
- # we avoid calculating len(sequence) if possible, because for lazy
933
- # sequences, calculating the length of a sequence can be expensive.
934
- if stop > 0:
935
- try: sequence[stop-1]
936
- except IndexError: stop = len(sequence)
937
-
938
- # Make sure start isn't past stop.
939
- start = min(start, stop)
940
-
941
- # That's all folks!
942
- return start, stop
943
-
944
- ######################################################################
945
- # Permission Checking
946
- ######################################################################
947
-
948
- def is_writable(path):
949
- # Ensure that it exists.
950
- if not os.path.exists(path):
951
- return False
952
-
953
- # If we're on a posix system, check its permissions.
954
- if hasattr(os, 'getuid'):
955
- statdata = os.stat(path)
956
- perm = stat.S_IMODE(statdata.st_mode)
957
- # is it world-writable?
958
- if (perm & 0o002):
959
- return True
960
- # do we own it?
961
- elif statdata.st_uid == os.getuid() and (perm & 0o200):
962
- return True
963
- # are we in a group that can write to it?
964
- elif (statdata.st_gid in [os.getgid()] + os.getgroups()) \
965
- and (perm & 0o020):
966
- return True
967
- # otherwise, we can't write to it.
968
- else:
969
- return False
970
-
971
- # Otherwise, we'll assume it's writable.
972
- # [xx] should we do other checks on other platforms?
973
- return True
974
-
975
- ######################################################################
976
- # NLTK Error reporting
977
- ######################################################################
978
-
979
- def raise_unorderable_types(ordering, a, b):
980
- raise TypeError("unorderable types: %s() %s %s()" % (type(a).__name__, ordering, type(b).__name__))
981
-
982
-
1
+ # Natural Language Toolkit: Internal utility functions
2
+ #
3
+ # Copyright (C) 2001-2018 NLTK Project
4
+ # Author: Steven Bird <stevenbird1@gmail.com>
5
+ # Edward Loper <edloper@gmail.com>
6
+ # Nitin Madnani <nmadnani@ets.org>
7
+ # URL: <http://nltk.org/>
8
+ # For license information, see LICENSE.TXT
9
+ from __future__ import print_function
10
+
11
+ import subprocess
12
+ import os
13
+ import fnmatch
14
+ import re
15
+ import warnings
16
+ import textwrap
17
+ import types
18
+ import sys
19
+ import stat
20
+ import locale
21
+
22
+ # Use the c version of ElementTree, which is faster, if possible:
23
+ try:
24
+ from xml.etree import cElementTree as ElementTree
25
+ except ImportError:
26
+ from xml.etree import ElementTree
27
+
28
+ from six import string_types
29
+
30
+ from nltk import __file__
31
+ from nltk import compat
32
+
33
+ ##########################################################################
34
+ # Java Via Command-Line
35
+ ##########################################################################
36
+
37
+ _java_bin = None
38
+ _java_options = []
39
+ # [xx] add classpath option to config_java?
40
+ def config_java(bin=None, options=None, verbose=False):
41
+ """
42
+ Configure nltk's java interface, by letting nltk know where it can
43
+ find the Java binary, and what extra options (if any) should be
44
+ passed to Java when it is run.
45
+
46
+ :param bin: The full path to the Java binary. If not specified,
47
+ then nltk will search the system for a Java binary; and if
48
+ one is not found, it will raise a ``LookupError`` exception.
49
+ :type bin: str
50
+ :param options: A list of options that should be passed to the
51
+ Java binary when it is called. A common value is
52
+ ``'-Xmx512m'``, which tells Java binary to increase
53
+ the maximum heap size to 512 megabytes. If no options are
54
+ specified, then do not modify the options list.
55
+ :type options: list(str)
56
+ """
57
+ global _java_bin, _java_options
58
+ _java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe'])
59
+
60
+ if options is not None:
61
+ if isinstance(options, string_types):
62
+ options = options.split()
63
+ _java_options = list(options)
64
+
65
+ def java(cmd, classpath=None, stdin=None, stdout=None, stderr=None,
66
+ blocking=True):
67
+ """
68
+ Execute the given java command, by opening a subprocess that calls
69
+ Java. If java has not yet been configured, it will be configured
70
+ by calling ``config_java()`` with no arguments.
71
+
72
+ :param cmd: The java command that should be called, formatted as
73
+ a list of strings. Typically, the first string will be the name
74
+ of the java class; and the remaining strings will be arguments
75
+ for that java class.
76
+ :type cmd: list(str)
77
+
78
+ :param classpath: A ``':'`` separated list of directories, JAR
79
+ archives, and ZIP archives to search for class files.
80
+ :type classpath: str
81
+
82
+ :param stdin, stdout, stderr: Specify the executed programs'
83
+ standard input, standard output and standard error file
84
+ handles, respectively. Valid values are ``subprocess.PIPE``,
85
+ an existing file descriptor (a positive integer), an existing
86
+ file object, and None. ``subprocess.PIPE`` indicates that a
87
+ new pipe to the child should be created. With None, no
88
+ redirection will occur; the child's file handles will be
89
+ inherited from the parent. Additionally, stderr can be
90
+ ``subprocess.STDOUT``, which indicates that the stderr data
91
+ from the applications should be captured into the same file
92
+ handle as for stdout.
93
+
94
+ :param blocking: If ``false``, then return immediately after
95
+ spawning the subprocess. In this case, the return value is
96
+ the ``Popen`` object, and not a ``(stdout, stderr)`` tuple.
97
+
98
+ :return: If ``blocking=True``, then return a tuple ``(stdout,
99
+ stderr)``, containing the stdout and stderr outputs generated
100
+ by the java command if the ``stdout`` and ``stderr`` parameters
101
+ were set to ``subprocess.PIPE``; or None otherwise. If
102
+ ``blocking=False``, then return a ``subprocess.Popen`` object.
103
+
104
+ :raise OSError: If the java command returns a nonzero return code.
105
+ """
106
+ if stdin == 'pipe': stdin = subprocess.PIPE
107
+ if stdout == 'pipe': stdout = subprocess.PIPE
108
+ if stderr == 'pipe': stderr = subprocess.PIPE
109
+ if isinstance(cmd, string_types):
110
+ raise TypeError('cmd should be a list of strings')
111
+
112
+ # Make sure we know where a java binary is.
113
+ if _java_bin is None:
114
+ config_java()
115
+
116
+ # Set up the classpath.
117
+ if isinstance(classpath, string_types):
118
+ classpaths=[classpath]
119
+ else:
120
+ classpaths=list(classpath)
121
+ classpath=os.path.pathsep.join(classpaths)
122
+
123
+ # Construct the full command string.
124
+ cmd = list(cmd)
125
+ cmd = ['-cp', classpath] + cmd
126
+ cmd = [_java_bin] + _java_options + cmd
127
+
128
+ # Call java via a subprocess
129
+ p = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr)
130
+ if not blocking: return p
131
+ (stdout, stderr) = p.communicate()
132
+
133
+ # Check the return code.
134
+ if p.returncode != 0:
135
+ print(_decode_stdoutdata(stderr))
136
+ raise OSError('Java command failed : ' + str(cmd))
137
+
138
+ return (stdout, stderr)
139
+
140
+ if 0:
141
+ #config_java(options='-Xmx512m')
142
+ # Write:
143
+ #java('weka.classifiers.bayes.NaiveBayes',
144
+ # ['-d', '/tmp/names.model', '-t', '/tmp/train.arff'],
145
+ # classpath='/Users/edloper/Desktop/weka/weka.jar')
146
+ # Read:
147
+ (a,b) = java(['weka.classifiers.bayes.NaiveBayes',
148
+ '-l', '/tmp/names.model', '-T', '/tmp/test.arff',
149
+ '-p', '0'],#, '-distribution'],
150
+ classpath='/Users/edloper/Desktop/weka/weka.jar')
151
+
152
+
153
+ ######################################################################
154
+ # Parsing
155
+ ######################################################################
156
+
157
+ class ReadError(ValueError):
158
+ """
159
+ Exception raised by read_* functions when they fail.
160
+ :param position: The index in the input string where an error occurred.
161
+ :param expected: What was expected when an error occurred.
162
+ """
163
+ def __init__(self, expected, position):
164
+ ValueError.__init__(self, expected, position)
165
+ self.expected = expected
166
+ self.position = position
167
+ def __str__(self):
168
+ return 'Expected %s at %s' % (self.expected, self.position)
169
+
170
+ _STRING_START_RE = re.compile(r"[uU]?[rR]?(\"\"\"|\'\'\'|\"|\')")
171
+ def read_str(s, start_position):
172
+ """
173
+ If a Python string literal begins at the specified position in the
174
+ given string, then return a tuple ``(val, end_position)``
175
+ containing the value of the string literal and the position where
176
+ it ends. Otherwise, raise a ``ReadError``.
177
+
178
+ :param s: A string that will be checked to see if within which a
179
+ Python string literal exists.
180
+ :type s: str
181
+
182
+ :param start_position: The specified beginning position of the string ``s``
183
+ to begin regex matching.
184
+ :type start_position: int
185
+
186
+ :return: A tuple containing the matched string literal evaluated as a
187
+ string and the end position of the string literal.
188
+ :rtype: tuple(str, int)
189
+
190
+ :raise ReadError: If the ``_STRING_START_RE`` regex doesn't return a
191
+ match in ``s`` at ``start_position``, i.e., open quote. If the
192
+ ``_STRING_END_RE`` regex doesn't return a match in ``s`` at the
193
+ end of the first match, i.e., close quote.
194
+ :raise ValueError: If an invalid string (i.e., contains an invalid
195
+ escape sequence) is passed into the ``eval``.
196
+
197
+ :Example:
198
+ >>> from nltk.internals import read_str
199
+ >>> read_str('"Hello", World!', 0)
200
+ ('Hello', 7)
201
+
202
+ """
203
+ # Read the open quote, and any modifiers.
204
+ m = _STRING_START_RE.match(s, start_position)
205
+ if not m: raise ReadError('open quote', start_position)
206
+ quotemark = m.group(1)
207
+
208
+ # Find the close quote.
209
+ _STRING_END_RE = re.compile(r'\\|%s' % quotemark)
210
+ position = m.end()
211
+ while True:
212
+ match = _STRING_END_RE.search(s, position)
213
+ if not match: raise ReadError('close quote', position)
214
+ if match.group(0) == '\\': position = match.end()+1
215
+ else: break
216
+
217
+ # Process it, using eval. Strings with invalid escape sequences
218
+ # might raise ValueEerror.
219
+ try:
220
+ return eval(s[start_position:match.end()]), match.end()
221
+ except ValueError as e:
222
+ raise ReadError('invalid string (%s)' % e)
223
+
224
+ _READ_INT_RE = re.compile(r'-?\d+')
225
+ def read_int(s, start_position):
226
+ """
227
+ If an integer begins at the specified position in the given
228
+ string, then return a tuple ``(val, end_position)`` containing the
229
+ value of the integer and the position where it ends. Otherwise,
230
+ raise a ``ReadError``.
231
+
232
+ :param s: A string that will be checked to see if within which a
233
+ Python integer exists.
234
+ :type s: str
235
+
236
+ :param start_position: The specified beginning position of the string ``s``
237
+ to begin regex matching.
238
+ :type start_position: int
239
+
240
+ :return: A tuple containing the matched integer casted to an int,
241
+ and the end position of the int in ``s``.
242
+ :rtype: tuple(int, int)
243
+
244
+ :raise ReadError: If the ``_READ_INT_RE`` regex doesn't return a
245
+ match in ``s`` at ``start_position``.
246
+
247
+ :Example:
248
+ >>> from nltk.internals import read_int
249
+ >>> read_int('42 is the answer', 0)
250
+ (42, 2)
251
+
252
+ """
253
+ m = _READ_INT_RE.match(s, start_position)
254
+ if not m: raise ReadError('integer', start_position)
255
+ return int(m.group()), m.end()
256
+
257
+ _READ_NUMBER_VALUE = re.compile(r'-?(\d*)([.]?\d*)?')
258
+ def read_number(s, start_position):
259
+ """
260
+ If an integer or float begins at the specified position in the
261
+ given string, then return a tuple ``(val, end_position)``
262
+ containing the value of the number and the position where it ends.
263
+ Otherwise, raise a ``ReadError``.
264
+
265
+ :param s: A string that will be checked to see if within which a
266
+ Python number exists.
267
+ :type s: str
268
+
269
+ :param start_position: The specified beginning position of the string ``s``
270
+ to begin regex matching.
271
+ :type start_position: int
272
+
273
+ :return: A tuple containing the matched number casted to a ``float``,
274
+ and the end position of the number in ``s``.
275
+ :rtype: tuple(float, int)
276
+
277
+ :raise ReadError: If the ``_READ_NUMBER_VALUE`` regex doesn't return a
278
+ match in ``s`` at ``start_position``.
279
+
280
+ :Example:
281
+ >>> from nltk.internals import read_number
282
+ >>> read_number('Pi is 3.14159', 6)
283
+ (3.14159, 13)
284
+
285
+ """
286
+ m = _READ_NUMBER_VALUE.match(s, start_position)
287
+ if not m or not (m.group(1) or m.group(2)):
288
+ raise ReadError('number', start_position)
289
+ if m.group(2): return float(m.group()), m.end()
290
+ else: return int(m.group()), m.end()
291
+
292
+
293
+
294
+ ######################################################################
295
+ # Check if a method has been overridden
296
+ ######################################################################
297
+
298
+ def overridden(method):
299
+ """
300
+ :return: True if ``method`` overrides some method with the same
301
+ name in a base class. This is typically used when defining
302
+ abstract base classes or interfaces, to allow subclasses to define
303
+ either of two related methods:
304
+
305
+ >>> class EaterI:
306
+ ... '''Subclass must define eat() or batch_eat().'''
307
+ ... def eat(self, food):
308
+ ... if overridden(self.batch_eat):
309
+ ... return self.batch_eat([food])[0]
310
+ ... else:
311
+ ... raise NotImplementedError()
312
+ ... def batch_eat(self, foods):
313
+ ... return [self.eat(food) for food in foods]
314
+
315
+ :type method: instance method
316
+ """
317
+ # [xx] breaks on classic classes!
318
+ if isinstance(method, types.MethodType) and compat.get_im_class(method) is not None:
319
+ name = method.__name__
320
+ funcs = [cls.__dict__[name]
321
+ for cls in _mro(compat.get_im_class(method))
322
+ if name in cls.__dict__]
323
+ return len(funcs) > 1
324
+ else:
325
+ raise TypeError('Expected an instance method.')
326
+
327
+ def _mro(cls):
328
+ """
329
+ Return the method resolution order for ``cls`` -- i.e., a list
330
+ containing ``cls`` and all its base classes, in the order in which
331
+ they would be checked by ``getattr``. For new-style classes, this
332
+ is just cls.__mro__. For classic classes, this can be obtained by
333
+ a depth-first left-to-right traversal of ``__bases__``.
334
+ """
335
+ if isinstance(cls, type):
336
+ return cls.__mro__
337
+ else:
338
+ mro = [cls]
339
+ for base in cls.__bases__: mro.extend(_mro(base))
340
+ return mro
341
+
342
+ ######################################################################
343
+ # Deprecation decorator & base class
344
+ ######################################################################
345
+ # [xx] dedent msg first if it comes from a docstring.
346
+
347
+ def _add_epytext_field(obj, field, message):
348
+ """Add an epytext @field to a given object's docstring."""
349
+ indent = ''
350
+ # If we already have a docstring, then add a blank line to separate
351
+ # it from the new field, and check its indentation.
352
+ if obj.__doc__:
353
+ obj.__doc__ = obj.__doc__.rstrip()+'\n\n'
354
+ indents = re.findall(r'(?<=\n)[ ]+(?!\s)', obj.__doc__.expandtabs())
355
+ if indents: indent = min(indents)
356
+ # If we don't have a docstring, add an empty one.
357
+ else:
358
+ obj.__doc__ = ''
359
+
360
+ obj.__doc__ += textwrap.fill('@%s: %s' % (field, message),
361
+ initial_indent=indent,
362
+ subsequent_indent=indent+' ')
363
+
364
+ def deprecated(message):
365
+ """
366
+ A decorator used to mark functions as deprecated. This will cause
367
+ a warning to be printed the when the function is used. Usage:
368
+
369
+ >>> from nltk.internals import deprecated
370
+ >>> @deprecated('Use foo() instead')
371
+ ... def bar(x):
372
+ ... print(x/10)
373
+
374
+ """
375
+
376
+ def decorator(func):
377
+ msg = ("Function %s() has been deprecated. %s"
378
+ % (func.__name__, message))
379
+ msg = '\n' + textwrap.fill(msg, initial_indent=' ',
380
+ subsequent_indent=' ')
381
+ def newFunc(*args, **kwargs):
382
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
383
+ return func(*args, **kwargs)
384
+
385
+ # Copy the old function's name, docstring, & dict
386
+ newFunc.__dict__.update(func.__dict__)
387
+ newFunc.__name__ = func.__name__
388
+ newFunc.__doc__ = func.__doc__
389
+ newFunc.__deprecated__ = True
390
+ # Add a @deprecated field to the docstring.
391
+ _add_epytext_field(newFunc, 'deprecated', message)
392
+ return newFunc
393
+ return decorator
394
+
395
+ class Deprecated(object):
396
+ """
397
+ A base class used to mark deprecated classes. A typical usage is to
398
+ alert users that the name of a class has changed:
399
+
400
+ >>> from nltk.internals import Deprecated
401
+ >>> class NewClassName(object):
402
+ ... pass # All logic goes here.
403
+ ...
404
+ >>> class OldClassName(Deprecated, NewClassName):
405
+ ... "Use NewClassName instead."
406
+
407
+ The docstring of the deprecated class will be used in the
408
+ deprecation warning message.
409
+ """
410
+ def __new__(cls, *args, **kwargs):
411
+ # Figure out which class is the deprecated one.
412
+ dep_cls = None
413
+ for base in _mro(cls):
414
+ if Deprecated in base.__bases__:
415
+ dep_cls = base; break
416
+ assert dep_cls, 'Unable to determine which base is deprecated.'
417
+
418
+ # Construct an appropriate warning.
419
+ doc = dep_cls.__doc__ or ''.strip()
420
+ # If there's a @deprecated field, strip off the field marker.
421
+ doc = re.sub(r'\A\s*@deprecated:', r'', doc)
422
+ # Strip off any indentation.
423
+ doc = re.sub(r'(?m)^\s*', '', doc)
424
+ # Construct a 'name' string.
425
+ name = 'Class %s' % dep_cls.__name__
426
+ if cls != dep_cls:
427
+ name += ' (base class for %s)' % cls.__name__
428
+ # Put it all together.
429
+ msg = '%s has been deprecated. %s' % (name, doc)
430
+ # Wrap it.
431
+ msg = '\n' + textwrap.fill(msg, initial_indent=' ',
432
+ subsequent_indent=' ')
433
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
434
+ # Do the actual work of __new__.
435
+ return object.__new__(cls)
436
+
437
+ ##########################################################################
438
+ # COUNTER, FOR UNIQUE NAMING
439
+ ##########################################################################
440
+
441
+ class Counter:
442
+ """
443
+ A counter that auto-increments each time its value is read.
444
+ """
445
+ def __init__(self, initial_value=0):
446
+ self._value = initial_value
447
+ def get(self):
448
+ self._value += 1
449
+ return self._value
450
+
451
+ ##########################################################################
452
+ # Search for files/binaries
453
+ ##########################################################################
454
+
455
+ def find_file_iter(filename, env_vars=(), searchpath=(),
456
+ file_names=None, url=None, verbose=False, finding_dir=False):
457
+ """
458
+ Search for a file to be used by nltk.
459
+
460
+ :param filename: The name or path of the file.
461
+ :param env_vars: A list of environment variable names to check.
462
+ :param file_names: A list of alternative file names to check.
463
+ :param searchpath: List of directories to search.
464
+ :param url: URL presented to user for download help.
465
+ :param verbose: Whether or not to print path when a file is found.
466
+ """
467
+ file_names = [filename] + (file_names or [])
468
+ assert isinstance(filename, string_types)
469
+ assert not isinstance(file_names, string_types)
470
+ assert not isinstance(searchpath, string_types)
471
+ if isinstance(env_vars, string_types):
472
+ env_vars = env_vars.split()
473
+ yielded = False
474
+
475
+ # File exists, no magic
476
+ for alternative in file_names:
477
+ path_to_file = os.path.join(filename, alternative)
478
+ if os.path.isfile(path_to_file):
479
+ if verbose:
480
+ print('[Found %s: %s]' % (filename, path_to_file))
481
+ yielded = True
482
+ yield path_to_file
483
+ # Check the bare alternatives
484
+ if os.path.isfile(alternative):
485
+ if verbose:
486
+ print('[Found %s: %s]' % (filename, alternative))
487
+ yielded = True
488
+ yield alternative
489
+ # Check if the alternative is inside a 'file' directory
490
+ path_to_file = os.path.join(filename, 'file', alternative)
491
+ if os.path.isfile(path_to_file):
492
+ if verbose:
493
+ print('[Found %s: %s]' % (filename, path_to_file))
494
+ yielded = True
495
+ yield path_to_file
496
+
497
+ # Check environment variables
498
+ for env_var in env_vars:
499
+ if env_var in os.environ:
500
+ if finding_dir: # This is to file a directory instead of file
501
+ yielded = True
502
+ yield os.environ[env_var]
503
+
504
+ for env_dir in os.environ[env_var].split(os.pathsep):
505
+ # Check if the environment variable contains a direct path to the bin
506
+ if os.path.isfile(env_dir):
507
+ if verbose:
508
+ print('[Found %s: %s]'%(filename, env_dir))
509
+ yielded = True
510
+ yield env_dir
511
+ # Check if the possible bin names exist inside the environment variable directories
512
+ for alternative in file_names:
513
+ path_to_file = os.path.join(env_dir, alternative)
514
+ if os.path.isfile(path_to_file):
515
+ if verbose:
516
+ print('[Found %s: %s]'%(filename, path_to_file))
517
+ yielded = True
518
+ yield path_to_file
519
+ # Check if the alternative is inside a 'file' directory
520
+ # path_to_file = os.path.join(env_dir, 'file', alternative)
521
+
522
+ # Check if the alternative is inside a 'bin' directory
523
+ path_to_file = os.path.join(env_dir, 'bin', alternative)
524
+
525
+ if os.path.isfile(path_to_file):
526
+ if verbose:
527
+ print('[Found %s: %s]' % (filename, path_to_file))
528
+ yielded = True
529
+ yield path_to_file
530
+
531
+ # Check the path list.
532
+ for directory in searchpath:
533
+ for alternative in file_names:
534
+ path_to_file = os.path.join(directory, alternative)
535
+ if os.path.isfile(path_to_file):
536
+ yielded = True
537
+ yield path_to_file
538
+
539
+ # If we're on a POSIX system, then try using the 'which' command
540
+ # to find the file.
541
+ if os.name == 'posix':
542
+ for alternative in file_names:
543
+ try:
544
+ p = subprocess.Popen(['which', alternative],
545
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
546
+ stdout, stderr = p.communicate()
547
+ path = _decode_stdoutdata(stdout).strip()
548
+ if path.endswith(alternative) and os.path.exists(path):
549
+ if verbose:
550
+ print('[Found %s: %s]' % (filename, path))
551
+ yielded = True
552
+ yield path
553
+ except (KeyboardInterrupt, SystemExit, OSError):
554
+ raise
555
+ except:
556
+ pass
557
+
558
+ if not yielded:
559
+ msg = ("NLTK was unable to find the %s file!" "\nUse software specific "
560
+ "configuration paramaters" % filename)
561
+ if env_vars: msg += ' or set the %s environment variable' % env_vars[0]
562
+ msg += '.'
563
+ if searchpath:
564
+ msg += '\n\n Searched in:'
565
+ msg += ''.join('\n - %s' % d for d in searchpath)
566
+ if url: msg += ('\n\n For more information on %s, see:\n <%s>' %
567
+ (filename, url))
568
+ div = '='*75
569
+ raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
570
+
571
+
572
+ def find_file(filename, env_vars=(), searchpath=(),
573
+ file_names=None, url=None, verbose=False):
574
+ return next(find_file_iter(filename, env_vars, searchpath,
575
+ file_names, url, verbose))
576
+
577
+
578
+ def find_dir(filename, env_vars=(), searchpath=(),
579
+ file_names=None, url=None, verbose=False):
580
+ return next(find_file_iter(filename, env_vars, searchpath,
581
+ file_names, url, verbose, finding_dir=True))
582
+
583
+
584
+ def find_binary_iter(name, path_to_bin=None, env_vars=(), searchpath=(),
585
+ binary_names=None, url=None, verbose=False):
586
+ """
587
+ Search for a file to be used by nltk.
588
+
589
+ :param name: The name or path of the file.
590
+ :param path_to_bin: The user-supplied binary location (deprecated)
591
+ :param env_vars: A list of environment variable names to check.
592
+ :param file_names: A list of alternative file names to check.
593
+ :param searchpath: List of directories to search.
594
+ :param url: URL presented to user for download help.
595
+ :param verbose: Whether or not to print path when a file is found.
596
+ """
597
+ for file in find_file_iter(path_to_bin or name, env_vars, searchpath, binary_names,
598
+ url, verbose):
599
+ yield file
600
+
601
+ def find_binary(name, path_to_bin=None, env_vars=(), searchpath=(),
602
+ binary_names=None, url=None, verbose=False):
603
+ return next(find_binary_iter(name, path_to_bin, env_vars, searchpath,
604
+ binary_names, url, verbose))
605
+
606
+ def find_jar_iter(name_pattern, path_to_jar=None, env_vars=(),
607
+ searchpath=(), url=None, verbose=False, is_regex=False):
608
+ """
609
+ Search for a jar that is used by nltk.
610
+
611
+ :param name_pattern: The name of the jar file
612
+ :param path_to_jar: The user-supplied jar location, or None.
613
+ :param env_vars: A list of environment variable names to check
614
+ in addition to the CLASSPATH variable which is
615
+ checked by default.
616
+ :param searchpath: List of directories to search.
617
+ :param is_regex: Whether name is a regular expression.
618
+ """
619
+
620
+ assert isinstance(name_pattern, string_types)
621
+ assert not isinstance(searchpath, string_types)
622
+ if isinstance(env_vars, string_types):
623
+ env_vars = env_vars.split()
624
+ yielded = False
625
+
626
+ # Make sure we check the CLASSPATH first
627
+ env_vars = ['CLASSPATH'] + list(env_vars)
628
+
629
+ # If an explicit location was given, then check it, and yield it if
630
+ # it's present; otherwise, complain.
631
+ if path_to_jar is not None:
632
+ if os.path.isfile(path_to_jar):
633
+ yielded = True
634
+ yield path_to_jar
635
+ else:
636
+ raise LookupError('Could not find %s jar file at %s' %
637
+ (name_pattern, path_to_jar))
638
+
639
+ # Check environment variables
640
+ for env_var in env_vars:
641
+ if env_var in os.environ:
642
+ if env_var == 'CLASSPATH':
643
+ classpath = os.environ['CLASSPATH']
644
+ for cp in classpath.split(os.path.pathsep):
645
+ if os.path.isfile(cp):
646
+ filename=os.path.basename(cp)
647
+ if is_regex and re.match(name_pattern, filename) or \
648
+ (not is_regex and filename == name_pattern):
649
+ if verbose:
650
+ print('[Found %s: %s]' % (name_pattern, cp))
651
+ yielded = True
652
+ yield cp
653
+ # The case where user put directory containing the jar file in the classpath
654
+ if os.path.isdir(cp):
655
+ if not is_regex:
656
+ if os.path.isfile(os.path.join(cp,name_pattern)):
657
+ if verbose:
658
+ print('[Found %s: %s]' % (name_pattern, cp))
659
+ yielded = True
660
+ yield os.path.join(cp,name_pattern)
661
+ else:
662
+ # Look for file using regular expression
663
+ for file_name in os.listdir(cp):
664
+ if re.match(name_pattern,file_name):
665
+ if verbose:
666
+ print('[Found %s: %s]' % (name_pattern, os.path.join(cp,file_name)))
667
+ yielded = True
668
+ yield os.path.join(cp,file_name)
669
+
670
+ else:
671
+ jar_env = os.environ[env_var]
672
+ jar_iter = ((os.path.join(jar_env, path_to_jar) for path_to_jar in os.listdir(jar_env))
673
+ if os.path.isdir(jar_env) else (jar_env,))
674
+ for path_to_jar in jar_iter:
675
+ if os.path.isfile(path_to_jar):
676
+ filename=os.path.basename(path_to_jar)
677
+ if is_regex and re.match(name_pattern, filename) or \
678
+ (not is_regex and filename == name_pattern):
679
+ if verbose:
680
+ print('[Found %s: %s]' % (name_pattern, path_to_jar))
681
+ yielded = True
682
+ yield path_to_jar
683
+
684
+ # Check the path list.
685
+ for directory in searchpath:
686
+ if is_regex:
687
+ for filename in os.listdir(directory):
688
+ path_to_jar = os.path.join(directory, filename)
689
+ if os.path.isfile(path_to_jar):
690
+ if re.match(name_pattern, filename):
691
+ if verbose:
692
+ print('[Found %s: %s]' % (filename, path_to_jar))
693
+ yielded = True
694
+ yield path_to_jar
695
+ else:
696
+ path_to_jar = os.path.join(directory, name_pattern)
697
+ if os.path.isfile(path_to_jar):
698
+ if verbose:
699
+ print('[Found %s: %s]' % (name_pattern, path_to_jar))
700
+ yielded = True
701
+ yield path_to_jar
702
+
703
+ if not yielded:
704
+ # If nothing was found, raise an error
705
+ msg = ("NLTK was unable to find %s!" % name_pattern)
706
+ if env_vars: msg += ' Set the %s environment variable' % env_vars[0]
707
+ msg = textwrap.fill(msg+'.', initial_indent=' ',
708
+ subsequent_indent=' ')
709
+ if searchpath:
710
+ msg += '\n\n Searched in:'
711
+ msg += ''.join('\n - %s' % d for d in searchpath)
712
+ if url:
713
+ msg += ('\n\n For more information, on %s, see:\n <%s>' %
714
+ (name_pattern, url))
715
+ div = '='*75
716
+ raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
717
+
718
+ def find_jar(name_pattern, path_to_jar=None, env_vars=(),
719
+ searchpath=(), url=None, verbose=False, is_regex=False):
720
+ return next(find_jar_iter(name_pattern, path_to_jar, env_vars,
721
+ searchpath, url, verbose, is_regex))
722
+
723
+
724
+ def find_jars_within_path(path_to_jars):
725
+ return [os.path.join(root, filename)
726
+ for root, dirnames, filenames in os.walk(path_to_jars)
727
+ for filename in fnmatch.filter(filenames, '*.jar')]
728
+
729
+ def _decode_stdoutdata(stdoutdata):
730
+ """ Convert data read from stdout/stderr to unicode """
731
+ if not isinstance(stdoutdata, bytes):
732
+ return stdoutdata
733
+
734
+ encoding = getattr(sys.__stdout__, "encoding", locale.getpreferredencoding())
735
+ if encoding is None:
736
+ return stdoutdata.decode()
737
+ return stdoutdata.decode(encoding)
738
+
739
+ ##########################################################################
740
+ # Import Stdlib Module
741
+ ##########################################################################
742
+
743
+ def import_from_stdlib(module):
744
+ """
745
+ When python is run from within the nltk/ directory tree, the
746
+ current directory is included at the beginning of the search path.
747
+ Unfortunately, that means that modules within nltk can sometimes
748
+ shadow standard library modules. As an example, the stdlib
749
+ 'inspect' module will attempt to import the stdlib 'tokenize'
750
+ module, but will instead end up importing NLTK's 'tokenize' module
751
+ instead (causing the import to fail).
752
+ """
753
+ old_path = sys.path
754
+ sys.path = [d for d in sys.path if d not in ('', '.')]
755
+ m = __import__(module)
756
+ sys.path = old_path
757
+ return m
758
+
759
+
760
+ ##########################################################################
761
+ # Wrapper for ElementTree Elements
762
+ ##########################################################################
763
+
764
+ @compat.python_2_unicode_compatible
765
+ class ElementWrapper(object):
766
+ """
767
+ A wrapper around ElementTree Element objects whose main purpose is
768
+ to provide nicer __repr__ and __str__ methods. In addition, any
769
+ of the wrapped Element's methods that return other Element objects
770
+ are overridden to wrap those values before returning them.
771
+
772
+ This makes Elements more convenient to work with in
773
+ interactive sessions and doctests, at the expense of some
774
+ efficiency.
775
+ """
776
+
777
+ # Prevent double-wrapping:
778
+ def __new__(cls, etree):
779
+ """
780
+ Create and return a wrapper around a given Element object.
781
+ If ``etree`` is an ``ElementWrapper``, then ``etree`` is
782
+ returned as-is.
783
+ """
784
+ if isinstance(etree, ElementWrapper):
785
+ return etree
786
+ else:
787
+ return object.__new__(ElementWrapper)
788
+
789
+ def __init__(self, etree):
790
+ r"""
791
+ Initialize a new Element wrapper for ``etree``.
792
+
793
+ If ``etree`` is a string, then it will be converted to an
794
+ Element object using ``ElementTree.fromstring()`` first:
795
+
796
+ >>> ElementWrapper("<test></test>")
797
+ <Element "<?xml version='1.0' encoding='utf8'?>\n<test />">
798
+
799
+ """
800
+ if isinstance(etree, string_types):
801
+ etree = ElementTree.fromstring(etree)
802
+ self.__dict__['_etree'] = etree
803
+
804
+ def unwrap(self):
805
+ """
806
+ Return the Element object wrapped by this wrapper.
807
+ """
808
+ return self._etree
809
+
810
+ ##////////////////////////////////////////////////////////////
811
+ #{ String Representation
812
+ ##////////////////////////////////////////////////////////////
813
+
814
+ def __repr__(self):
815
+ s = ElementTree.tostring(self._etree, encoding='utf8').decode('utf8')
816
+ if len(s) > 60:
817
+ e = s.rfind('<')
818
+ if (len(s)-e) > 30: e = -20
819
+ s = '%s...%s' % (s[:30], s[e:])
820
+ return '<Element %r>' % s
821
+
822
+ def __str__(self):
823
+ """
824
+ :return: the result of applying ``ElementTree.tostring()`` to
825
+ the wrapped Element object.
826
+ """
827
+ return ElementTree.tostring(self._etree, encoding='utf8').decode('utf8').rstrip()
828
+
829
+ ##////////////////////////////////////////////////////////////
830
+ #{ Element interface Delegation (pass-through)
831
+ ##////////////////////////////////////////////////////////////
832
+
833
+ def __getattr__(self, attrib):
834
+ return getattr(self._etree, attrib)
835
+
836
+ def __setattr__(self, attr, value):
837
+ return setattr(self._etree, attr, value)
838
+
839
+ def __delattr__(self, attr):
840
+ return delattr(self._etree, attr)
841
+
842
+ def __setitem__(self, index, element):
843
+ self._etree[index] = element
844
+
845
+ def __delitem__(self, index):
846
+ del self._etree[index]
847
+
848
+ def __setslice__(self, start, stop, elements):
849
+ self._etree[start:stop] = elements
850
+
851
+ def __delslice__(self, start, stop):
852
+ del self._etree[start:stop]
853
+
854
+ def __len__(self):
855
+ return len(self._etree)
856
+
857
+ ##////////////////////////////////////////////////////////////
858
+ #{ Element interface Delegation (wrap result)
859
+ ##////////////////////////////////////////////////////////////
860
+
861
+ def __getitem__(self, index):
862
+ return ElementWrapper(self._etree[index])
863
+
864
+ def __getslice__(self, start, stop):
865
+ return [ElementWrapper(elt) for elt in self._etree[start:stop]]
866
+
867
+ def getchildren(self):
868
+ return [ElementWrapper(elt) for elt in self._etree]
869
+
870
+ def getiterator(self, tag=None):
871
+ return (ElementWrapper(elt)
872
+ for elt in self._etree.getiterator(tag))
873
+
874
+ def makeelement(self, tag, attrib):
875
+ return ElementWrapper(self._etree.makeelement(tag, attrib))
876
+
877
+ def find(self, path):
878
+ elt = self._etree.find(path)
879
+ if elt is None: return elt
880
+ else: return ElementWrapper(elt)
881
+
882
+ def findall(self, path):
883
+ return [ElementWrapper(elt) for elt in self._etree.findall(path)]
884
+
885
+ ######################################################################
886
+ # Helper for Handling Slicing
887
+ ######################################################################
888
+
889
+ def slice_bounds(sequence, slice_obj, allow_step=False):
890
+ """
891
+ Given a slice, return the corresponding (start, stop) bounds,
892
+ taking into account None indices and negative indices. The
893
+ following guarantees are made for the returned start and stop values:
894
+
895
+ - 0 <= start <= len(sequence)
896
+ - 0 <= stop <= len(sequence)
897
+ - start <= stop
898
+
899
+ :raise ValueError: If ``slice_obj.step`` is not None.
900
+ :param allow_step: If true, then the slice object may have a
901
+ non-None step. If it does, then return a tuple
902
+ (start, stop, step).
903
+ """
904
+ start, stop = (slice_obj.start, slice_obj.stop)
905
+
906
+ # If allow_step is true, then include the step in our return
907
+ # value tuple.
908
+ if allow_step:
909
+ step = slice_obj.step
910
+ if step is None: step = 1
911
+ # Use a recursive call without allow_step to find the slice
912
+ # bounds. If step is negative, then the roles of start and
913
+ # stop (in terms of default values, etc), are swapped.
914
+ if step < 0:
915
+ start, stop = slice_bounds(sequence, slice(stop, start))
916
+ else:
917
+ start, stop = slice_bounds(sequence, slice(start, stop))
918
+ return start, stop, step
919
+
920
+ # Otherwise, make sure that no non-default step value is used.
921
+ elif slice_obj.step not in (None, 1):
922
+ raise ValueError('slices with steps are not supported by %s' %
923
+ sequence.__class__.__name__)
924
+
925
+ # Supply default offsets.
926
+ if start is None: start = 0
927
+ if stop is None: stop = len(sequence)
928
+
929
+ # Handle negative indices.
930
+ if start < 0: start = max(0, len(sequence)+start)
931
+ if stop < 0: stop = max(0, len(sequence)+stop)
932
+
933
+ # Make sure stop doesn't go past the end of the list. Note that
934
+ # we avoid calculating len(sequence) if possible, because for lazy
935
+ # sequences, calculating the length of a sequence can be expensive.
936
+ if stop > 0:
937
+ try: sequence[stop-1]
938
+ except IndexError: stop = len(sequence)
939
+
940
+ # Make sure start isn't past stop.
941
+ start = min(start, stop)
942
+
943
+ # That's all folks!
944
+ return start, stop
945
+
946
+ ######################################################################
947
+ # Permission Checking
948
+ ######################################################################
949
+
950
+ def is_writable(path):
951
+ # Ensure that it exists.
952
+ if not os.path.exists(path):
953
+ return False
954
+
955
+ # If we're on a posix system, check its permissions.
956
+ if hasattr(os, 'getuid'):
957
+ statdata = os.stat(path)
958
+ perm = stat.S_IMODE(statdata.st_mode)
959
+ # is it world-writable?
960
+ if (perm & 0o002):
961
+ return True
962
+ # do we own it?
963
+ elif statdata.st_uid == os.getuid() and (perm & 0o200):
964
+ return True
965
+ # are we in a group that can write to it?
966
+ elif (statdata.st_gid in [os.getgid()] + os.getgroups()) \
967
+ and (perm & 0o020):
968
+ return True
969
+ # otherwise, we can't write to it.
970
+ else:
971
+ return False
972
+
973
+ # Otherwise, we'll assume it's writable.
974
+ # [xx] should we do other checks on other platforms?
975
+ return True
976
+
977
+ ######################################################################
978
+ # NLTK Error reporting
979
+ ######################################################################
980
+
981
+ def raise_unorderable_types(ordering, a, b):
982
+ raise TypeError("unorderable types: %s() %s %s()" % (type(a).__name__, ordering, type(b).__name__))