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,968 +1,968 @@
1
- # Natural Language Toolkit: WordNet Browser Application
2
- #
3
- # Copyright (C) 2001-2015 NLTK Project
4
- # Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
5
- # Paul Bone <pbone@students.csse.unimelb.edu.au>
6
- # URL: <http://nltk.org/>
7
- # For license information, see LICENSE.TXT
8
-
9
- """
10
- A WordNet Browser application which launches the default browser
11
- (if it is not already running) and opens a new tab with a connection
12
- to http://localhost:port/ . It also starts an HTTP server on the
13
- specified port and begins serving browser requests. The default
14
- port is 8000. (For command-line help, run "python wordnet -h")
15
- This application requires that the user's web browser supports
16
- Javascript.
17
-
18
- BrowServer is a server for browsing the NLTK Wordnet database It first
19
- launches a browser client to be used for browsing and then starts
20
- serving the requests of that and maybe other clients
21
-
22
- Usage::
23
-
24
- browserver.py -h
25
- browserver.py [-s] [-p <port>]
26
-
27
- Options::
28
-
29
- -h or --help
30
- Display this help message.
31
-
32
- -l <file> or --log-file <file>
33
- Logs messages to the given file, If this option is not specified
34
- messages are silently dropped.
35
-
36
- -p <port> or --port <port>
37
- Run the web server on this TCP port, defaults to 8000.
38
-
39
- -s or --server-mode
40
- Do not start a web browser, and do not allow a user to
41
- shotdown the server through the web interface.
42
- """
43
- # TODO: throughout this package variable names and docstrings need
44
- # modifying to be compliant with NLTK's coding standards. Tests also
45
- # need to be develop to ensure this continues to work in the face of
46
- # changes to other NLTK packages.
47
- from __future__ import print_function
48
-
49
- # Allow this program to run inside the NLTK source tree.
50
- from sys import path
51
-
52
- import os
53
- import sys
54
- from sys import argv
55
- from collections import defaultdict
56
- import webbrowser
57
- import datetime
58
- import re
59
- import threading
60
- import time
61
- import getopt
62
- import base64
63
- import pickle
64
- import copy
65
-
66
- from nltk import compat
67
- from nltk.corpus import wordnet as wn
68
- from nltk.corpus.reader.wordnet import Synset, Lemma
69
-
70
- if compat.PY3:
71
- from http.server import HTTPServer, BaseHTTPRequestHandler
72
- else:
73
- from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
74
-
75
- # now included in local file
76
- # from util import html_header, html_trailer, \
77
- # get_static_index_page, get_static_page_by_path, \
78
- # page_from_word, page_from_href
79
-
80
- firstClient = True
81
-
82
- # True if we're not also running a web browser. The value f server_mode
83
- # gets set by demo().
84
- server_mode = None
85
-
86
- # If set this is a file object for writting log messages.
87
- logfile = None
88
-
89
-
90
- class MyServerHandler(BaseHTTPRequestHandler):
91
-
92
- def do_HEAD(self):
93
- self.send_head()
94
-
95
- def do_GET(self):
96
- global firstClient
97
- sp = self.path[1:]
98
- if compat.unquote_plus(sp) == 'SHUTDOWN THE SERVER':
99
- if server_mode:
100
- page = "Server must be killed with SIGTERM."
101
- type = "text/plain"
102
- else:
103
- print('Server shutting down!')
104
- os._exit(0)
105
-
106
- elif sp == '': # First request.
107
- type = 'text/html'
108
- if not server_mode and firstClient:
109
- firstClient = False
110
- page = get_static_index_page(True)
111
- else:
112
- page = get_static_index_page(False)
113
- word = 'green'
114
-
115
- elif sp.endswith('.html'): # Trying to fetch a HTML file TODO:
116
- type = 'text/html'
117
- usp = compat.unquote_plus(sp)
118
- if usp == 'NLTK Wordnet Browser Database Info.html':
119
- word = '* Database Info *'
120
- if os.path.isfile(usp):
121
- with open(usp, 'r') as infile:
122
- page = infile.read()
123
- else:
124
- page = (html_header % word) + \
125
- '<p>The database info file:'\
126
- '<p><b>' + usp + '</b>' + \
127
- '<p>was not found. Run this:' + \
128
- '<p><b>python dbinfo_html.py</b>' + \
129
- '<p>to produce it.' + html_trailer
130
- else:
131
- # Handle files here.
132
- word = sp
133
- page = get_static_page_by_path(usp)
134
- elif sp.startswith("search"):
135
- # This doesn't seem to work with MWEs.
136
- type = 'text/html'
137
- parts = (sp.split("?")[1]).split("&")
138
- word = [p.split("=")[1].replace("+", " ")
139
- for p in parts if p.startswith("nextWord")][0]
140
- page, word = page_from_word(word)
141
- elif sp.startswith("lookup_"):
142
- # TODO add a variation of this that takes a non ecoded word or MWE.
143
- type = 'text/html'
144
- sp = sp[len("lookup_"):]
145
- page, word = page_from_href(sp)
146
- elif sp == "start_page":
147
- # if this is the first request we should display help
148
- # information, and possibly set a default word.
149
- type = 'text/html'
150
- page, word = page_from_word("wordnet")
151
- else:
152
- type = 'text/plain'
153
- page = "Could not parse request: '%s'" % sp
154
-
155
- # Send result.
156
- self.send_head(type)
157
- self.wfile.write(page.encode('utf8'))
158
-
159
-
160
- def send_head(self, type=None):
161
- self.send_response(200)
162
- self.send_header('Content-type', type)
163
- self.end_headers()
164
-
165
- def log_message(self, format, *args):
166
- global logfile
167
-
168
- if logfile:
169
- logfile.write(
170
- "%s - - [%s] %s\n" %
171
- (self.address_string(),
172
- self.log_date_time_string(),
173
- format%args))
174
-
175
-
176
- def get_unique_counter_from_url(sp):
177
- """
178
- Extract the unique counter from the URL if it has one. Otherwise return
179
- null.
180
- """
181
- pos = sp.rfind('%23')
182
- if pos != -1:
183
- return int(sp[(pos + 3):])
184
- else:
185
- return None
186
-
187
-
188
- def wnb(port=8000, runBrowser=True, logfilename=None):
189
- """
190
- Run NLTK Wordnet Browser Server.
191
-
192
- :param port: The port number for the server to listen on, defaults to
193
- 8000
194
- :type port: int
195
-
196
- :param runBrowser: True to start a web browser and point it at the web
197
- server.
198
- :type runBrowser: bool
199
- """
200
- # The webbrowser module is unpredictable, typically it blocks if it uses
201
- # a console web browser, and doesn't block if it uses a GUI webbrowser,
202
- # so we need to force it to have a clear correct behaviour.
203
- #
204
- # Normally the server should run for as long as the user wants. they
205
- # should idealy be able to control this from the UI by closing the
206
- # window or tab. Second best would be clicking a button to say
207
- # 'Shutdown' that first shutsdown the server and closes the window or
208
- # tab, or exits the text-mode browser. Both of these are unfreasable.
209
- #
210
- # The next best alternative is to start the server, have it close when
211
- # it receives SIGTERM (default), and run the browser as well. The user
212
- # may have to shutdown both programs.
213
- #
214
- # Since webbrowser may block, and the webserver will block, we must run
215
- # them in separate threads.
216
- #
217
- global server_mode, logfile
218
- server_mode = not runBrowser
219
-
220
- # Setup logging.
221
- if logfilename:
222
- try:
223
- logfile = open(logfilename, "a", 1) # 1 means 'line buffering'
224
- except IOError as e:
225
- sys.stderr.write("Couldn't open %s for writing: %s",
226
- logfilename, e)
227
- sys.exit(1)
228
- else:
229
- logfile = None
230
-
231
- # Compute URL and start web browser
232
- url = 'http://localhost:' + str(port)
233
-
234
- server_ready = None
235
- browser_thread = None
236
-
237
- if runBrowser:
238
- server_ready = threading.Event()
239
- browser_thread = startBrowser(url, server_ready)
240
-
241
- # Start the server.
242
- server = HTTPServer(('', port), MyServerHandler)
243
- if logfile:
244
- logfile.write(
245
- 'NLTK Wordnet browser server running serving: %s\n' % url)
246
- if runBrowser:
247
- server_ready.set()
248
-
249
- try:
250
- server.serve_forever()
251
- except KeyboardInterrupt:
252
- pass
253
-
254
- if runBrowser:
255
- browser_thread.join()
256
-
257
- if logfile:
258
- logfile.close()
259
-
260
-
261
- def startBrowser(url, server_ready):
262
- def run():
263
- server_ready.wait()
264
- time.sleep(1) # Wait a little bit more, there's still the chance of
265
- # a race condition.
266
- webbrowser.open(url, new = 2, autoraise = 1)
267
- t = threading.Thread(target=run)
268
- t.start()
269
- return t
270
-
271
- #####################################################################
272
- # Utilities
273
- #####################################################################
274
-
275
-
276
- """
277
- WordNet Browser Utilities.
278
-
279
- This provides a backend to both wxbrowse and browserver.py.
280
- """
281
-
282
-
283
- ################################################################################
284
- #
285
- # Main logic for wordnet browser.
286
- #
287
-
288
- # This is wrapped inside a function since wn is only available if the
289
- # WordNet corpus is installed.
290
- def _pos_tuples():
291
- return [
292
- (wn.NOUN,'N','noun'),
293
- (wn.VERB,'V','verb'),
294
- (wn.ADJ,'J','adj'),
295
- (wn.ADV,'R','adv')]
296
-
297
- def _pos_match(pos_tuple):
298
- """
299
- This function returns the complete pos tuple for the partial pos
300
- tuple given to it. It attempts to match it against the first
301
- non-null component of the given pos tuple.
302
- """
303
- if pos_tuple[0] == 's':
304
- pos_tuple = ('a', pos_tuple[1], pos_tuple[2])
305
- for n,x in enumerate(pos_tuple):
306
- if x is not None:
307
- break
308
- for pt in _pos_tuples():
309
- if pt[n] == pos_tuple[n]: return pt
310
- return None
311
-
312
-
313
- HYPONYM = 0
314
- HYPERNYM = 1
315
- CLASS_REGIONAL = 2
316
- PART_HOLONYM = 3
317
- PART_MERONYM = 4
318
- ATTRIBUTE = 5
319
- SUBSTANCE_HOLONYM = 6
320
- SUBSTANCE_MERONYM = 7
321
- MEMBER_HOLONYM = 8
322
- MEMBER_MERONYM = 9
323
- VERB_GROUP = 10
324
- INSTANCE_HYPONYM = 12
325
- INSTANCE_HYPERNYM = 13
326
- CAUSE = 14
327
- ALSO_SEE = 15
328
- SIMILAR = 16
329
- ENTAILMENT = 17
330
- ANTONYM = 18
331
- FRAMES = 19
332
- PERTAINYM = 20
333
-
334
- CLASS_CATEGORY = 21
335
- CLASS_USAGE = 22
336
- CLASS_REGIONAL = 23
337
- CLASS_USAGE = 24
338
- CLASS_CATEGORY = 11
339
-
340
- DERIVATIONALLY_RELATED_FORM = 25
341
-
342
- INDIRECT_HYPERNYMS = 26
343
-
344
-
345
- def lemma_property(word, synset, func):
346
-
347
- def flattern(l):
348
- if l == []:
349
- return []
350
- else:
351
- return l[0] + flattern(l[1:])
352
-
353
- return flattern([func(l) for l in synset.lemmas if l.name == word])
354
-
355
-
356
- def rebuild_tree(orig_tree):
357
- node = orig_tree[0]
358
- children = orig_tree[1:]
359
- return (node, [rebuild_tree(t) for t in children])
360
-
361
-
362
- def get_relations_data(word, synset):
363
- """
364
- Get synset relations data for a synset. Note that this doesn't
365
- yet support things such as full hyponym vs direct hyponym.
366
- """
367
- if synset.pos() == wn.NOUN:
368
- return ((HYPONYM, 'Hyponyms',
369
- synset.hyponyms()),
370
- (INSTANCE_HYPONYM , 'Instance hyponyms',
371
- synset.instance_hyponyms()),
372
- (HYPERNYM, 'Direct hypernyms',
373
- synset.hypernyms()),
374
- (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
375
- rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
376
- # hypernyms', 'Sister terms',
377
- (INSTANCE_HYPERNYM , 'Instance hypernyms',
378
- synset.instance_hypernyms()),
379
- # (CLASS_REGIONAL, ['domain term region'], ),
380
- (PART_HOLONYM, 'Part holonyms',
381
- synset.part_holonyms()),
382
- (PART_MERONYM, 'Part meronyms',
383
- synset.part_meronyms()),
384
- (SUBSTANCE_HOLONYM, 'Substance holonyms',
385
- synset.substance_holonyms()),
386
- (SUBSTANCE_MERONYM, 'Substance meronyms',
387
- synset.substance_meronyms()),
388
- (MEMBER_HOLONYM, 'Member holonyms',
389
- synset.member_holonyms()),
390
- (MEMBER_MERONYM, 'Member meronyms',
391
- synset.member_meronyms()),
392
- (ATTRIBUTE, 'Attributes',
393
- synset.attributes()),
394
- (ANTONYM, "Antonyms",
395
- lemma_property(word, synset, lambda l: l.antonyms())),
396
- (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
397
- lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
398
- elif synset.pos() == wn.VERB:
399
- return ((ANTONYM, 'Antonym',
400
- lemma_property(word, synset, lambda l: l.antonyms())),
401
- (HYPONYM, 'Hyponym',
402
- synset.hyponyms()),
403
- (HYPERNYM, 'Direct hypernyms',
404
- synset.hypernyms()),
405
- (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
406
- rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
407
- (ENTAILMENT, 'Entailments',
408
- synset.entailments()),
409
- (CAUSE, 'Causes',
410
- synset.causes()),
411
- (ALSO_SEE, 'Also see',
412
- synset.also_sees()),
413
- (VERB_GROUP, 'Verb Groups',
414
- synset.verb_groups()),
415
- (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
416
- lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
417
- elif synset.pos() == wn.ADJ or synset.pos == wn.ADJ_SAT:
418
- return ((ANTONYM, 'Antonym',
419
- lemma_property(word, synset, lambda l: l.antonyms())),
420
- (SIMILAR, 'Similar to',
421
- synset.similar_tos()),
422
- # Participle of verb - not supported by corpus
423
- (PERTAINYM, 'Pertainyms',
424
- lemma_property(word, synset, lambda l: l.pertainyms())),
425
- (ATTRIBUTE, 'Attributes',
426
- synset.attributes()),
427
- (ALSO_SEE, 'Also see',
428
- synset.also_sees()))
429
- elif synset.pos() == wn.ADV:
430
- # This is weird. adverbs such as 'quick' and 'fast' don't seem
431
- # to have antonyms returned by the corpus.a
432
- return ((ANTONYM, 'Antonym',
433
- lemma_property(word, synset, lambda l: l.antonyms())),)
434
- # Derived from adjective - not supported by corpus
435
- else:
436
- raise TypeError("Unhandles synset POS type: " + str(synset.pos()))
437
-
438
-
439
- html_header = '''
440
- <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
441
- 'http://www.w3.org/TR/html4/strict.dtd'>
442
- <html>
443
- <head>
444
- <meta name='generator' content=
445
- 'HTML Tidy for Windows (vers 14 February 2006), see www.w3.org'>
446
- <meta http-equiv='Content-Type' content=
447
- 'text/html; charset=us-ascii'>
448
- <title>NLTK Wordnet Browser display of: %s</title></head>
449
- <body bgcolor='#F5F5F5' text='#000000'>
450
- '''
451
- html_trailer = '''
452
- </body>
453
- </html>
454
- '''
455
-
456
- explanation = '''
457
- <h3>Search Help</h3>
458
- <ul><li>The display below the line is an example of the output the browser
459
- shows you when you enter a search word. The search word was <b>green</b>.</li>
460
- <li>The search result shows for different parts of speech the <b>synsets</b>
461
- i.e. different meanings for the word.</li>
462
- <li>All underlined texts are hypertext links. There are two types of links:
463
- word links and others. Clicking a word link carries out a search for the word
464
- in the Wordnet database.</li>
465
- <li>Clicking a link of the other type opens a display section of data attached
466
- to that link. Clicking that link a second time closes the section again.</li>
467
- <li>Clicking <u>S:</u> opens a section showing the relations for that synset.
468
- </li>
469
- <li>Clicking on a relation name opens a section that displays the associated
470
- synsets.</li>
471
- <li>Type a search word in the <b>Word</b> field and start the search by the
472
- <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
473
- </ul>
474
- <hr width='100%'>
475
- '''
476
-
477
- # HTML oriented functions
478
-
479
- def _bold(txt): return '<b>%s</b>' % txt
480
-
481
- def _center(txt): return '<center>%s</center>' % txt
482
-
483
- def _hlev(n,txt): return '<h%d>%s</h%d>' % (n,txt,n)
484
-
485
- def _italic(txt): return '<i>%s</i>' % txt
486
-
487
- def _li(txt): return '<li>%s</li>' % txt
488
-
489
- def pg(word, body):
490
- '''
491
- Return a HTML page of NLTK Browser format constructed from the
492
- word and body
493
-
494
- :param word: The word that the body corresponds to
495
- :type word: str
496
- :param body: The HTML body corresponding to the word
497
- :type body: str
498
- :return: a HTML page for the word-body combination
499
- :rtype: str
500
- '''
501
- return (html_header % word) + body + html_trailer
502
-
503
- def _ul(txt): return '<ul>' + txt + '</ul>'
504
-
505
- def _abbc(txt):
506
- """
507
- abbc = asterisks, breaks, bold, center
508
- """
509
- return _center(_bold('<br>'*10 + '*'*10 + ' ' + txt + ' ' + '*'*10))
510
-
511
- full_hyponym_cont_text = \
512
- _ul(_li(_italic('(has full hyponym continuation)'))) + '\n'
513
-
514
-
515
- def _get_synset(synset_key):
516
- """
517
- The synset key is the unique name of the synset, this can be
518
- retrived via synset.name()
519
- """
520
- return wn.synset(synset_key)
521
-
522
- def _collect_one_synset(word, synset, synset_relations):
523
- '''
524
- Returns the HTML string for one synset or word
525
-
526
- :param word: the current word
527
- :type word: str
528
- :param synset: a synset
529
- :type synset: synset
530
- :param synset_relations: information about which synset relations
531
- to display.
532
- :type synset_relations: dict(synset_key, set(relation_id))
533
- :return: The HTML string built for this synset
534
- :rtype: str
535
- '''
536
- if isinstance(synset, tuple): # It's a word
537
- raise NotImplementedError("word not supported by _collect_one_synset")
538
-
539
- typ = 'S'
540
- pos_tuple = _pos_match((synset.pos(), None, None))
541
- assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
542
- descr = pos_tuple[2]
543
- ref = copy.deepcopy(Reference(word, synset_relations))
544
- ref.toggle_synset(synset)
545
- synset_label = typ + ";"
546
- if synset.name() in synset_relations:
547
- synset_label = _bold(synset_label)
548
- s = '<li>%s (%s) ' % (make_lookup_link(ref, synset_label), descr)
549
- def format_lemma(w):
550
- w = w.replace('_', ' ')
551
- if w.lower() == word:
552
- return _bold(w)
553
- else:
554
- ref = Reference(w)
555
- return make_lookup_link(ref, w)
556
-
557
- s += ', '.join(format_lemma(l.name()) for l in synset.lemmas())
558
-
559
- gl = " (%s) <i>%s</i> " % \
560
- (synset.definition(),
561
- "; ".join("\"%s\"" % e for e in synset.examples()))
562
- return s + gl + _synset_relations(word, synset, synset_relations) + '</li>\n'
563
-
564
- def _collect_all_synsets(word, pos, synset_relations=dict()):
565
- """
566
- Return a HTML unordered list of synsets for the given word and
567
- part of speech.
568
- """
569
- return '<ul>%s\n</ul>\n' % \
570
- ''.join((_collect_one_synset(word, synset, synset_relations)
571
- for synset
572
- in wn.synsets(word, pos)))
573
-
574
- def _synset_relations(word, synset, synset_relations):
575
- '''
576
- Builds the HTML string for the relations of a synset
577
-
578
- :param word: The current word
579
- :type word: str
580
- :param synset: The synset for which we're building the relations.
581
- :type synset: Synset
582
- :param synset_relations: synset keys and relation types for which to display relations.
583
- :type synset_relations: dict(synset_key, set(relation_type))
584
- :return: The HTML for a synset's relations
585
- :rtype: str
586
- '''
587
-
588
- if not synset.name() in synset_relations:
589
- return ""
590
- ref = Reference(word, synset_relations)
591
-
592
- def relation_html(r):
593
- if isinstance(r, Synset):
594
- return make_lookup_link(Reference(r.lemma_names()[0]), r.lemma_names()[0])
595
- elif isinstance(r, Lemma):
596
- return relation_html(r.synset())
597
- elif isinstance(r, tuple):
598
- # It's probably a tuple containing a Synset and a list of
599
- # similar tuples. This forms a tree of synsets.
600
- return "%s\n<ul>%s</ul>\n" % \
601
- (relation_html(r[0]),
602
- ''.join('<li>%s</li>\n' % relation_html(sr) for sr in r[1]))
603
- else:
604
- raise TypeError("r must be a synset, lemma or list, it was: type(r) = %s, r = %s" % (type(r), r))
605
-
606
- def make_synset_html(db_name, disp_name, rels):
607
- synset_html = '<i>%s</i>\n' % \
608
- make_lookup_link(
609
- copy.deepcopy(ref).toggle_synset_relation(synset, db_name).encode(),
610
- disp_name)
611
-
612
- if db_name in ref.synset_relations[synset.name()]:
613
- synset_html += '<ul>%s</ul>\n' % \
614
- ''.join("<li>%s</li>\n" % relation_html(r) for r in rels)
615
-
616
- return synset_html
617
-
618
- html = '<ul>' + \
619
- '\n'.join(("<li>%s</li>" % make_synset_html(*rel_data) for rel_data
620
- in get_relations_data(word, synset)
621
- if rel_data[2] != [])) + \
622
- '</ul>'
623
-
624
- return html
625
-
626
-
627
- class Reference(object):
628
- """
629
- A reference to a page that may be generated by page_word
630
- """
631
-
632
- def __init__(self, word, synset_relations=dict()):
633
- """
634
- Build a reference to a new page.
635
-
636
- word is the word or words (separated by commas) for which to
637
- search for synsets of
638
-
639
- synset_relations is a dictionary of synset keys to sets of
640
- synset relation identifaiers to unfold a list of synset
641
- relations for.
642
- """
643
- self.word = word
644
- self.synset_relations = synset_relations
645
-
646
- def encode(self):
647
- """
648
- Encode this reference into a string to be used in a URL.
649
- """
650
- # This uses a tuple rather than an object since the python
651
- # pickle representation is much smaller and there is no need
652
- # to represent the complete object.
653
- string = pickle.dumps((self.word, self.synset_relations), -1)
654
- return base64.urlsafe_b64encode(string).decode()
655
-
656
- @staticmethod
657
- def decode(string):
658
- """
659
- Decode a reference encoded with Reference.encode
660
- """
661
- string = base64.urlsafe_b64decode(string.encode())
662
- word, synset_relations = pickle.loads(string)
663
- return Reference(word, synset_relations)
664
-
665
- def toggle_synset_relation(self, synset, relation):
666
- """
667
- Toggle the display of the relations for the given synset and
668
- relation type.
669
-
670
- This function will throw a KeyError if the synset is currently
671
- not being displayed.
672
- """
673
- if relation in self.synset_relations[synset.name()]:
674
- self.synset_relations[synset.name()].remove(relation)
675
- else:
676
- self.synset_relations[synset.name()].add(relation)
677
-
678
- return self
679
-
680
- def toggle_synset(self, synset):
681
- """
682
- Toggle displaying of the relation types for the given synset
683
- """
684
- if synset.name() in self.synset_relations:
685
- del self.synset_relations[synset.name()]
686
- else:
687
- self.synset_relations[synset.name()] = set()
688
-
689
- return self
690
-
691
-
692
- def make_lookup_link(ref, label):
693
- return '<a href="lookup_%s">%s</a>' % (ref.encode(), label)
694
-
695
-
696
- def page_from_word(word):
697
- """
698
- Return a HTML page for the given word.
699
-
700
- :param word: The currently active word
701
- :type word: str
702
- :return: A tuple (page,word), where page is the new current HTML page
703
- to be sent to the browser and
704
- word is the new current word
705
- :rtype: A tuple (str,str)
706
- """
707
- return page_from_reference(Reference(word))
708
-
709
- def page_from_href(href):
710
- '''
711
- Returns a tuple of the HTML page built and the new current word
712
-
713
- :param href: The hypertext reference to be solved
714
- :type href: str
715
- :return: A tuple (page,word), where page is the new current HTML page
716
- to be sent to the browser and
717
- word is the new current word
718
- :rtype: A tuple (str,str)
719
- '''
720
- return page_from_reference(Reference.decode(href))
721
-
722
- def page_from_reference(href):
723
- '''
724
- Returns a tuple of the HTML page built and the new current word
725
-
726
- :param href: The hypertext reference to be solved
727
- :type href: str
728
- :return: A tuple (page,word), where page is the new current HTML page
729
- to be sent to the browser and
730
- word is the new current word
731
- :rtype: A tuple (str,str)
732
- '''
733
- word = href.word
734
- pos_forms = defaultdict(list)
735
- words = word.split(',')
736
- words = [w for w in [w.strip().lower().replace(' ', '_')
737
- for w in words]
738
- if w != ""]
739
- if len(words) == 0:
740
- # No words were found.
741
- return "", "Please specify a word to search for."
742
-
743
- # This looks up multiple words at once. This is probably not
744
- # necessary and may lead to problems.
745
- for w in words:
746
- for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]:
747
- form = wn.morphy(w, pos)
748
- if form and form not in pos_forms[pos]:
749
- pos_forms[pos].append(form)
750
- body = ''
751
- for pos,pos_str,name in _pos_tuples():
752
- if pos in pos_forms:
753
- body += _hlev(3, name) + '\n'
754
- for w in pos_forms[pos]:
755
- # Not all words of exc files are in the database, skip
756
- # to the next word if a KeyError is raised.
757
- try:
758
- body += _collect_all_synsets(w, pos, href.synset_relations)
759
- except KeyError:
760
- pass
761
- if not body:
762
- body = "The word or words '%s' where not found in the dictonary." % word
763
- return body, word
764
-
765
-
766
-
767
- #####################################################################
768
- # Static pages
769
- #####################################################################
770
-
771
- def get_static_page_by_path(path):
772
- """
773
- Return a static HTML page from the path given.
774
- """
775
- if path == "index_2.html":
776
- return get_static_index_page(False)
777
- elif path == "index.html":
778
- return get_static_index_page(True)
779
- elif path == "NLTK Wordnet Browser Database Info.html":
780
- return "Display of Wordnet Database Statistics is not supported"
781
- elif path == "upper_2.html":
782
- return get_static_upper_page(False)
783
- elif path == "upper.html":
784
- return get_static_upper_page(True)
785
- elif path == "web_help.html":
786
- return get_static_web_help_page()
787
- elif path == "wx_help.html":
788
- return get_static_wx_help_page()
789
- else:
790
- return "Internal error: Path for static page '%s' is unknown" % path
791
-
792
-
793
- def get_static_web_help_page():
794
- """
795
- Return the static web help page.
796
- """
797
- return \
798
- """
799
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
800
- <html>
801
- <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
802
- Copyright (C) 2001-2015 NLTK Project
803
- Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
804
- URL: <http://nltk.org/>
805
- For license information, see LICENSE.TXT -->
806
- <head>
807
- <meta http-equiv='Content-Type' content='text/html; charset=us-ascii'>
808
- <title>NLTK Wordnet Browser display of: * Help *</title>
809
- </head>
810
- <body bgcolor='#F5F5F5' text='#000000'>
811
- <h2>NLTK Wordnet Browser Help</h2>
812
- <p>The NLTK Wordnet Browser is a tool to use in browsing the Wordnet database. It tries to behave like the Wordnet project's web browser but the difference is that the NLTK Wordnet Browser uses a local Wordnet database.
813
- <p><b>You are using the Javascript client part of the NLTK Wordnet BrowseServer.</b> We assume your browser is in tab sheets enabled mode.</p>
814
- <p>For background information on Wordnet, see the Wordnet project home page: <a href="http://wordnet.princeton.edu/"><b> http://wordnet.princeton.edu/</b></a>. For more information on the NLTK project, see the project home:
815
- <a href="http://nltk.sourceforge.net/"><b>http://nltk.sourceforge.net/</b></a>. To get an idea of what the Wordnet version used by this browser includes choose <b>Show Database Info</b> from the <b>View</b> submenu.</p>
816
- <h3>Word search</h3>
817
- <p>The word to be searched is typed into the <b>New Word</b> field and the search started with Enter or by clicking the <b>Search</b> button. There is no uppercase/lowercase distinction: the search word is transformed to lowercase before the search.</p>
818
- <p>In addition, the word does not have to be in base form. The browser tries to find the possible base form(s) by making certain morphological substitutions. Typing <b>fLIeS</b> as an obscure example gives one <a href="MfLIeS">this</a>. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination.</p>
819
- <p>The result of a search is a display of one or more
820
- <b>synsets</b> for every part of speech in which a form of the
821
- search word was found to occur. A synset is a set of words
822
- having the same sense or meaning. Each word in a synset that is
823
- underlined is a hyperlink which can be clicked to trigger an
824
- automatic search for that word.</p>
825
- <p>Every synset has a hyperlink <b>S:</b> at the start of its
826
- display line. Clicking that symbol shows you the name of every
827
- <b>relation</b> that this synset is part of. Every relation name is a hyperlink that opens up a display for that relation. Clicking it another time closes the display again. Clicking another relation name on a line that has an opened relation closes the open relation and opens the clicked relation.</p>
828
- <p>It is also possible to give two or more words or collocations to be searched at the same time separating them with a comma like this <a href="Mcheer up,clear up">cheer up,clear up</a>, for example. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination. As you could see the search result includes the synsets found in the same order than the forms were given in the search field.</p>
829
- <p>
830
- There are also word level (lexical) relations recorded in the Wordnet database. Opening this kind of relation displays lines with a hyperlink <b>W:</b> at their beginning. Clicking this link shows more info on the word in question.</p>
831
- <h3>The Buttons</h3>
832
- <p>The <b>Search</b> and <b>Help</b> buttons need no more explanation. </p>
833
- <p>The <b>Show Database Info</b> button shows a collection of Wordnet database statistics.</p>
834
- <p>The <b>Shutdown the Server</b> button is shown for the first client of the BrowServer program i.e. for the client that is automatically launched when the BrowServer is started but not for the succeeding clients in order to protect the server from accidental shutdowns.
835
- </p></body>
836
- </html>
837
- """
838
-
839
-
840
- def get_static_welcome_message():
841
- """
842
- Get the static welcome page.
843
- """
844
- return \
845
- """
846
- <h3>Search Help</h3>
847
- <ul><li>The display below the line is an example of the output the browser
848
- shows you when you enter a search word. The search word was <b>green</b>.</li>
849
- <li>The search result shows for different parts of speech the <b>synsets</b>
850
- i.e. different meanings for the word.</li>
851
- <li>All underlined texts are hypertext links. There are two types of links:
852
- word links and others. Clicking a word link carries out a search for the word
853
- in the Wordnet database.</li>
854
- <li>Clicking a link of the other type opens a display section of data attached
855
- to that link. Clicking that link a second time closes the section again.</li>
856
- <li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
857
- <li>Clicking on a relation name opens a section that displays the associated
858
- synsets.</li>
859
- <li>Type a search word in the <b>Next Word</b> field and start the search by the
860
- <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
861
- </ul>
862
- """
863
-
864
- def get_static_index_page(with_shutdown):
865
- """
866
- Get the static index page.
867
- """
868
- template = \
869
- """
870
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
871
- <HTML>
872
- <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
873
- Copyright (C) 2001-2015 NLTK Project
874
- Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
875
- URL: <http://nltk.org/>
876
- For license information, see LICENSE.TXT -->
877
- <HEAD>
878
- <TITLE>NLTK Wordnet Browser</TITLE>
879
- </HEAD>
880
-
881
- <frameset rows="7%%,93%%">
882
- <frame src="%s" name="header">
883
- <frame src="start_page" name="body">
884
- </frameset>
885
- </HTML>
886
- """
887
- if with_shutdown:
888
- upper_link = "upper.html"
889
- else:
890
- upper_link = "upper_2.html"
891
-
892
- return template % upper_link
893
-
894
-
895
- def get_static_upper_page(with_shutdown):
896
- """
897
- Return the upper frame page,
898
-
899
- If with_shutdown is True then a 'shutdown' button is also provided
900
- to shutdown the server.
901
- """
902
- template = \
903
- """
904
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
905
- <html>
906
- <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
907
- Copyright (C) 2001-2015 NLTK Project
908
- Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
909
- URL: <http://nltk.org/>
910
- For license information, see LICENSE.TXT -->
911
- <head>
912
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
913
- <title>Untitled Document</title>
914
- </head>
915
- <body>
916
- <form method="GET" action="search" target="body">
917
- Current Word:&nbsp;<input type="text" id="currentWord" size="10" disabled>
918
- Next Word:&nbsp;<input type="text" id="nextWord" name="nextWord" size="10">
919
- <input name="searchButton" type="submit" value="Search">
920
- </form>
921
- <a target="body" href="web_help.html">Help</a>
922
- %s
923
-
924
- </body>
925
- </html>
926
- """
927
- if with_shutdown:
928
- shutdown_link = "<a href=\"SHUTDOWN THE SERVER\">Shutdown</a>"
929
- else:
930
- shutdown_link = ""
931
-
932
- return template % shutdown_link
933
-
934
-
935
-
936
- def usage():
937
- """
938
- Display the command line help message.
939
- """
940
- print(__doc__)
941
-
942
- def app():
943
- # Parse and interpret options.
944
- (opts, _) = getopt.getopt(argv[1:], "l:p:sh",
945
- ["logfile=", "port=", "server-mode", "help"])
946
- port = 8000
947
- server_mode = False
948
- help_mode = False
949
- logfilename = None
950
- for (opt, value) in opts:
951
- if (opt == "-l") or (opt == "--logfile"):
952
- logfilename = str(value)
953
- elif (opt == "-p") or (opt == "--port"):
954
- port = int(value)
955
- elif (opt == "-s") or (opt == "--server-mode"):
956
- server_mode = True
957
- elif (opt == "-h") or (opt == "--help"):
958
- help_mode = True
959
-
960
- if help_mode:
961
- usage()
962
- else:
963
- wnb(port, not server_mode, logfilename)
964
-
965
- if __name__ == '__main__':
966
- app()
967
-
968
- __all__ = ['app']
1
+ # Natural Language Toolkit: WordNet Browser Application
2
+ #
3
+ # Copyright (C) 2001-2018 NLTK Project
4
+ # Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
5
+ # Paul Bone <pbone@students.csse.unimelb.edu.au>
6
+ # URL: <http://nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ A WordNet Browser application which launches the default browser
11
+ (if it is not already running) and opens a new tab with a connection
12
+ to http://localhost:port/ . It also starts an HTTP server on the
13
+ specified port and begins serving browser requests. The default
14
+ port is 8000. (For command-line help, run "python wordnet -h")
15
+ This application requires that the user's web browser supports
16
+ Javascript.
17
+
18
+ BrowServer is a server for browsing the NLTK Wordnet database It first
19
+ launches a browser client to be used for browsing and then starts
20
+ serving the requests of that and maybe other clients
21
+
22
+ Usage::
23
+
24
+ browserver.py -h
25
+ browserver.py [-s] [-p <port>]
26
+
27
+ Options::
28
+
29
+ -h or --help
30
+ Display this help message.
31
+
32
+ -l <file> or --log-file <file>
33
+ Logs messages to the given file, If this option is not specified
34
+ messages are silently dropped.
35
+
36
+ -p <port> or --port <port>
37
+ Run the web server on this TCP port, defaults to 8000.
38
+
39
+ -s or --server-mode
40
+ Do not start a web browser, and do not allow a user to
41
+ shotdown the server through the web interface.
42
+ """
43
+ # TODO: throughout this package variable names and docstrings need
44
+ # modifying to be compliant with NLTK's coding standards. Tests also
45
+ # need to be develop to ensure this continues to work in the face of
46
+ # changes to other NLTK packages.
47
+ from __future__ import print_function
48
+
49
+ # Allow this program to run inside the NLTK source tree.
50
+ from sys import path
51
+
52
+ import os
53
+ import sys
54
+ from sys import argv
55
+ from collections import defaultdict
56
+ import webbrowser
57
+ import datetime
58
+ import re
59
+ import threading
60
+ import time
61
+ import getopt
62
+ import base64
63
+ import pickle
64
+ import copy
65
+
66
+ from six.moves.urllib.parse import unquote_plus
67
+
68
+ from nltk import compat
69
+ from nltk.corpus import wordnet as wn
70
+ from nltk.corpus.reader.wordnet import Synset, Lemma
71
+
72
+ if compat.PY3:
73
+ from http.server import HTTPServer, BaseHTTPRequestHandler
74
+ else:
75
+ from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
76
+
77
+ # now included in local file
78
+ # from util import html_header, html_trailer, \
79
+ # get_static_index_page, get_static_page_by_path, \
80
+ # page_from_word, page_from_href
81
+
82
+ firstClient = True
83
+
84
+ # True if we're not also running a web browser. The value f server_mode
85
+ # gets set by demo().
86
+ server_mode = None
87
+
88
+ # If set this is a file object for writting log messages.
89
+ logfile = None
90
+
91
+
92
+ class MyServerHandler(BaseHTTPRequestHandler):
93
+
94
+ def do_HEAD(self):
95
+ self.send_head()
96
+
97
+ def do_GET(self):
98
+ global firstClient
99
+ sp = self.path[1:]
100
+ if unquote_plus(sp) == 'SHUTDOWN THE SERVER':
101
+ if server_mode:
102
+ page = "Server must be killed with SIGTERM."
103
+ type = "text/plain"
104
+ else:
105
+ print('Server shutting down!')
106
+ os._exit(0)
107
+
108
+ elif sp == '': # First request.
109
+ type = 'text/html'
110
+ if not server_mode and firstClient:
111
+ firstClient = False
112
+ page = get_static_index_page(True)
113
+ else:
114
+ page = get_static_index_page(False)
115
+ word = 'green'
116
+
117
+ elif sp.endswith('.html'): # Trying to fetch a HTML file TODO:
118
+ type = 'text/html'
119
+ usp = unquote_plus(sp)
120
+ if usp == 'NLTK Wordnet Browser Database Info.html':
121
+ word = '* Database Info *'
122
+ if os.path.isfile(usp):
123
+ with open(usp, 'r') as infile:
124
+ page = infile.read()
125
+ else:
126
+ page = (html_header % word) + \
127
+ '<p>The database info file:'\
128
+ '<p><b>' + usp + '</b>' + \
129
+ '<p>was not found. Run this:' + \
130
+ '<p><b>python dbinfo_html.py</b>' + \
131
+ '<p>to produce it.' + html_trailer
132
+ else:
133
+ # Handle files here.
134
+ word = sp
135
+ page = get_static_page_by_path(usp)
136
+ elif sp.startswith("search"):
137
+ # This doesn't seem to work with MWEs.
138
+ type = 'text/html'
139
+ parts = (sp.split("?")[1]).split("&")
140
+ word = [p.split("=")[1].replace("+", " ")
141
+ for p in parts if p.startswith("nextWord")][0]
142
+ page, word = page_from_word(word)
143
+ elif sp.startswith("lookup_"):
144
+ # TODO add a variation of this that takes a non ecoded word or MWE.
145
+ type = 'text/html'
146
+ sp = sp[len("lookup_"):]
147
+ page, word = page_from_href(sp)
148
+ elif sp == "start_page":
149
+ # if this is the first request we should display help
150
+ # information, and possibly set a default word.
151
+ type = 'text/html'
152
+ page, word = page_from_word("wordnet")
153
+ else:
154
+ type = 'text/plain'
155
+ page = "Could not parse request: '%s'" % sp
156
+
157
+ # Send result.
158
+ self.send_head(type)
159
+ self.wfile.write(page.encode('utf8'))
160
+
161
+
162
+ def send_head(self, type=None):
163
+ self.send_response(200)
164
+ self.send_header('Content-type', type)
165
+ self.end_headers()
166
+
167
+ def log_message(self, format, *args):
168
+ global logfile
169
+
170
+ if logfile:
171
+ logfile.write(
172
+ "%s - - [%s] %s\n" %
173
+ (self.address_string(),
174
+ self.log_date_time_string(),
175
+ format%args))
176
+
177
+
178
+ def get_unique_counter_from_url(sp):
179
+ """
180
+ Extract the unique counter from the URL if it has one. Otherwise return
181
+ null.
182
+ """
183
+ pos = sp.rfind('%23')
184
+ if pos != -1:
185
+ return int(sp[(pos + 3):])
186
+ else:
187
+ return None
188
+
189
+
190
+ def wnb(port=8000, runBrowser=True, logfilename=None):
191
+ """
192
+ Run NLTK Wordnet Browser Server.
193
+
194
+ :param port: The port number for the server to listen on, defaults to
195
+ 8000
196
+ :type port: int
197
+
198
+ :param runBrowser: True to start a web browser and point it at the web
199
+ server.
200
+ :type runBrowser: bool
201
+ """
202
+ # The webbrowser module is unpredictable, typically it blocks if it uses
203
+ # a console web browser, and doesn't block if it uses a GUI webbrowser,
204
+ # so we need to force it to have a clear correct behaviour.
205
+ #
206
+ # Normally the server should run for as long as the user wants. they
207
+ # should idealy be able to control this from the UI by closing the
208
+ # window or tab. Second best would be clicking a button to say
209
+ # 'Shutdown' that first shutsdown the server and closes the window or
210
+ # tab, or exits the text-mode browser. Both of these are unfreasable.
211
+ #
212
+ # The next best alternative is to start the server, have it close when
213
+ # it receives SIGTERM (default), and run the browser as well. The user
214
+ # may have to shutdown both programs.
215
+ #
216
+ # Since webbrowser may block, and the webserver will block, we must run
217
+ # them in separate threads.
218
+ #
219
+ global server_mode, logfile
220
+ server_mode = not runBrowser
221
+
222
+ # Setup logging.
223
+ if logfilename:
224
+ try:
225
+ logfile = open(logfilename, "a", 1) # 1 means 'line buffering'
226
+ except IOError as e:
227
+ sys.stderr.write("Couldn't open %s for writing: %s",
228
+ logfilename, e)
229
+ sys.exit(1)
230
+ else:
231
+ logfile = None
232
+
233
+ # Compute URL and start web browser
234
+ url = 'http://localhost:' + str(port)
235
+
236
+ server_ready = None
237
+ browser_thread = None
238
+
239
+ if runBrowser:
240
+ server_ready = threading.Event()
241
+ browser_thread = startBrowser(url, server_ready)
242
+
243
+ # Start the server.
244
+ server = HTTPServer(('', port), MyServerHandler)
245
+ if logfile:
246
+ logfile.write(
247
+ 'NLTK Wordnet browser server running serving: %s\n' % url)
248
+ if runBrowser:
249
+ server_ready.set()
250
+
251
+ try:
252
+ server.serve_forever()
253
+ except KeyboardInterrupt:
254
+ pass
255
+
256
+ if runBrowser:
257
+ browser_thread.join()
258
+
259
+ if logfile:
260
+ logfile.close()
261
+
262
+
263
+ def startBrowser(url, server_ready):
264
+ def run():
265
+ server_ready.wait()
266
+ time.sleep(1) # Wait a little bit more, there's still the chance of
267
+ # a race condition.
268
+ webbrowser.open(url, new = 2, autoraise = 1)
269
+ t = threading.Thread(target=run)
270
+ t.start()
271
+ return t
272
+
273
+ #####################################################################
274
+ # Utilities
275
+ #####################################################################
276
+
277
+
278
+ """
279
+ WordNet Browser Utilities.
280
+
281
+ This provides a backend to both wxbrowse and browserver.py.
282
+ """
283
+
284
+ ################################################################################
285
+ #
286
+ # Main logic for wordnet browser.
287
+ #
288
+
289
+ # This is wrapped inside a function since wn is only available if the
290
+ # WordNet corpus is installed.
291
+ def _pos_tuples():
292
+ return [
293
+ (wn.NOUN,'N','noun'),
294
+ (wn.VERB,'V','verb'),
295
+ (wn.ADJ,'J','adj'),
296
+ (wn.ADV,'R','adv')]
297
+
298
+ def _pos_match(pos_tuple):
299
+ """
300
+ This function returns the complete pos tuple for the partial pos
301
+ tuple given to it. It attempts to match it against the first
302
+ non-null component of the given pos tuple.
303
+ """
304
+ if pos_tuple[0] == 's':
305
+ pos_tuple = ('a', pos_tuple[1], pos_tuple[2])
306
+ for n,x in enumerate(pos_tuple):
307
+ if x is not None:
308
+ break
309
+ for pt in _pos_tuples():
310
+ if pt[n] == pos_tuple[n]: return pt
311
+ return None
312
+
313
+
314
+ HYPONYM = 0
315
+ HYPERNYM = 1
316
+ CLASS_REGIONAL = 2
317
+ PART_HOLONYM = 3
318
+ PART_MERONYM = 4
319
+ ATTRIBUTE = 5
320
+ SUBSTANCE_HOLONYM = 6
321
+ SUBSTANCE_MERONYM = 7
322
+ MEMBER_HOLONYM = 8
323
+ MEMBER_MERONYM = 9
324
+ VERB_GROUP = 10
325
+ INSTANCE_HYPONYM = 12
326
+ INSTANCE_HYPERNYM = 13
327
+ CAUSE = 14
328
+ ALSO_SEE = 15
329
+ SIMILAR = 16
330
+ ENTAILMENT = 17
331
+ ANTONYM = 18
332
+ FRAMES = 19
333
+ PERTAINYM = 20
334
+
335
+ CLASS_CATEGORY = 21
336
+ CLASS_USAGE = 22
337
+ CLASS_REGIONAL = 23
338
+ CLASS_USAGE = 24
339
+ CLASS_CATEGORY = 11
340
+
341
+ DERIVATIONALLY_RELATED_FORM = 25
342
+
343
+ INDIRECT_HYPERNYMS = 26
344
+
345
+
346
+ def lemma_property(word, synset, func):
347
+
348
+ def flattern(l):
349
+ if l == []:
350
+ return []
351
+ else:
352
+ return l[0] + flattern(l[1:])
353
+
354
+ return flattern([func(l) for l in synset.lemmas if l.name == word])
355
+
356
+
357
+ def rebuild_tree(orig_tree):
358
+ node = orig_tree[0]
359
+ children = orig_tree[1:]
360
+ return (node, [rebuild_tree(t) for t in children])
361
+
362
+
363
+ def get_relations_data(word, synset):
364
+ """
365
+ Get synset relations data for a synset. Note that this doesn't
366
+ yet support things such as full hyponym vs direct hyponym.
367
+ """
368
+ if synset.pos() == wn.NOUN:
369
+ return ((HYPONYM, 'Hyponyms',
370
+ synset.hyponyms()),
371
+ (INSTANCE_HYPONYM , 'Instance hyponyms',
372
+ synset.instance_hyponyms()),
373
+ (HYPERNYM, 'Direct hypernyms',
374
+ synset.hypernyms()),
375
+ (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
376
+ rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
377
+ # hypernyms', 'Sister terms',
378
+ (INSTANCE_HYPERNYM , 'Instance hypernyms',
379
+ synset.instance_hypernyms()),
380
+ # (CLASS_REGIONAL, ['domain term region'], ),
381
+ (PART_HOLONYM, 'Part holonyms',
382
+ synset.part_holonyms()),
383
+ (PART_MERONYM, 'Part meronyms',
384
+ synset.part_meronyms()),
385
+ (SUBSTANCE_HOLONYM, 'Substance holonyms',
386
+ synset.substance_holonyms()),
387
+ (SUBSTANCE_MERONYM, 'Substance meronyms',
388
+ synset.substance_meronyms()),
389
+ (MEMBER_HOLONYM, 'Member holonyms',
390
+ synset.member_holonyms()),
391
+ (MEMBER_MERONYM, 'Member meronyms',
392
+ synset.member_meronyms()),
393
+ (ATTRIBUTE, 'Attributes',
394
+ synset.attributes()),
395
+ (ANTONYM, "Antonyms",
396
+ lemma_property(word, synset, lambda l: l.antonyms())),
397
+ (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
398
+ lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
399
+ elif synset.pos() == wn.VERB:
400
+ return ((ANTONYM, 'Antonym',
401
+ lemma_property(word, synset, lambda l: l.antonyms())),
402
+ (HYPONYM, 'Hyponym',
403
+ synset.hyponyms()),
404
+ (HYPERNYM, 'Direct hypernyms',
405
+ synset.hypernyms()),
406
+ (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
407
+ rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
408
+ (ENTAILMENT, 'Entailments',
409
+ synset.entailments()),
410
+ (CAUSE, 'Causes',
411
+ synset.causes()),
412
+ (ALSO_SEE, 'Also see',
413
+ synset.also_sees()),
414
+ (VERB_GROUP, 'Verb Groups',
415
+ synset.verb_groups()),
416
+ (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
417
+ lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
418
+ elif synset.pos() == wn.ADJ or synset.pos == wn.ADJ_SAT:
419
+ return ((ANTONYM, 'Antonym',
420
+ lemma_property(word, synset, lambda l: l.antonyms())),
421
+ (SIMILAR, 'Similar to',
422
+ synset.similar_tos()),
423
+ # Participle of verb - not supported by corpus
424
+ (PERTAINYM, 'Pertainyms',
425
+ lemma_property(word, synset, lambda l: l.pertainyms())),
426
+ (ATTRIBUTE, 'Attributes',
427
+ synset.attributes()),
428
+ (ALSO_SEE, 'Also see',
429
+ synset.also_sees()))
430
+ elif synset.pos() == wn.ADV:
431
+ # This is weird. adverbs such as 'quick' and 'fast' don't seem
432
+ # to have antonyms returned by the corpus.a
433
+ return ((ANTONYM, 'Antonym',
434
+ lemma_property(word, synset, lambda l: l.antonyms())),)
435
+ # Derived from adjective - not supported by corpus
436
+ else:
437
+ raise TypeError("Unhandles synset POS type: " + str(synset.pos()))
438
+
439
+
440
+ html_header = '''
441
+ <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
442
+ 'http://www.w3.org/TR/html4/strict.dtd'>
443
+ <html>
444
+ <head>
445
+ <meta name='generator' content=
446
+ 'HTML Tidy for Windows (vers 14 February 2006), see www.w3.org'>
447
+ <meta http-equiv='Content-Type' content=
448
+ 'text/html; charset=us-ascii'>
449
+ <title>NLTK Wordnet Browser display of: %s</title></head>
450
+ <body bgcolor='#F5F5F5' text='#000000'>
451
+ '''
452
+ html_trailer = '''
453
+ </body>
454
+ </html>
455
+ '''
456
+
457
+ explanation = '''
458
+ <h3>Search Help</h3>
459
+ <ul><li>The display below the line is an example of the output the browser
460
+ shows you when you enter a search word. The search word was <b>green</b>.</li>
461
+ <li>The search result shows for different parts of speech the <b>synsets</b>
462
+ i.e. different meanings for the word.</li>
463
+ <li>All underlined texts are hypertext links. There are two types of links:
464
+ word links and others. Clicking a word link carries out a search for the word
465
+ in the Wordnet database.</li>
466
+ <li>Clicking a link of the other type opens a display section of data attached
467
+ to that link. Clicking that link a second time closes the section again.</li>
468
+ <li>Clicking <u>S:</u> opens a section showing the relations for that synset.
469
+ </li>
470
+ <li>Clicking on a relation name opens a section that displays the associated
471
+ synsets.</li>
472
+ <li>Type a search word in the <b>Word</b> field and start the search by the
473
+ <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
474
+ </ul>
475
+ <hr width='100%'>
476
+ '''
477
+
478
+ # HTML oriented functions
479
+
480
+ def _bold(txt): return '<b>%s</b>' % txt
481
+
482
+ def _center(txt): return '<center>%s</center>' % txt
483
+
484
+ def _hlev(n,txt): return '<h%d>%s</h%d>' % (n,txt,n)
485
+
486
+ def _italic(txt): return '<i>%s</i>' % txt
487
+
488
+ def _li(txt): return '<li>%s</li>' % txt
489
+
490
+ def pg(word, body):
491
+ '''
492
+ Return a HTML page of NLTK Browser format constructed from the
493
+ word and body
494
+
495
+ :param word: The word that the body corresponds to
496
+ :type word: str
497
+ :param body: The HTML body corresponding to the word
498
+ :type body: str
499
+ :return: a HTML page for the word-body combination
500
+ :rtype: str
501
+ '''
502
+ return (html_header % word) + body + html_trailer
503
+
504
+ def _ul(txt): return '<ul>' + txt + '</ul>'
505
+
506
+ def _abbc(txt):
507
+ """
508
+ abbc = asterisks, breaks, bold, center
509
+ """
510
+ return _center(_bold('<br>'*10 + '*'*10 + ' ' + txt + ' ' + '*'*10))
511
+
512
+ full_hyponym_cont_text = \
513
+ _ul(_li(_italic('(has full hyponym continuation)'))) + '\n'
514
+
515
+
516
+ def _get_synset(synset_key):
517
+ """
518
+ The synset key is the unique name of the synset, this can be
519
+ retrived via synset.name()
520
+ """
521
+ return wn.synset(synset_key)
522
+
523
+ def _collect_one_synset(word, synset, synset_relations):
524
+ '''
525
+ Returns the HTML string for one synset or word
526
+
527
+ :param word: the current word
528
+ :type word: str
529
+ :param synset: a synset
530
+ :type synset: synset
531
+ :param synset_relations: information about which synset relations
532
+ to display.
533
+ :type synset_relations: dict(synset_key, set(relation_id))
534
+ :return: The HTML string built for this synset
535
+ :rtype: str
536
+ '''
537
+ if isinstance(synset, tuple): # It's a word
538
+ raise NotImplementedError("word not supported by _collect_one_synset")
539
+
540
+ typ = 'S'
541
+ pos_tuple = _pos_match((synset.pos(), None, None))
542
+ assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
543
+ descr = pos_tuple[2]
544
+ ref = copy.deepcopy(Reference(word, synset_relations))
545
+ ref.toggle_synset(synset)
546
+ synset_label = typ + ";"
547
+ if synset.name() in synset_relations:
548
+ synset_label = _bold(synset_label)
549
+ s = '<li>%s (%s) ' % (make_lookup_link(ref, synset_label), descr)
550
+ def format_lemma(w):
551
+ w = w.replace('_', ' ')
552
+ if w.lower() == word:
553
+ return _bold(w)
554
+ else:
555
+ ref = Reference(w)
556
+ return make_lookup_link(ref, w)
557
+
558
+ s += ', '.join(format_lemma(l.name()) for l in synset.lemmas())
559
+
560
+ gl = " (%s) <i>%s</i> " % \
561
+ (synset.definition(),
562
+ "; ".join("\"%s\"" % e for e in synset.examples()))
563
+ return s + gl + _synset_relations(word, synset, synset_relations) + '</li>\n'
564
+
565
+ def _collect_all_synsets(word, pos, synset_relations=dict()):
566
+ """
567
+ Return a HTML unordered list of synsets for the given word and
568
+ part of speech.
569
+ """
570
+ return '<ul>%s\n</ul>\n' % \
571
+ ''.join((_collect_one_synset(word, synset, synset_relations)
572
+ for synset
573
+ in wn.synsets(word, pos)))
574
+
575
+ def _synset_relations(word, synset, synset_relations):
576
+ '''
577
+ Builds the HTML string for the relations of a synset
578
+
579
+ :param word: The current word
580
+ :type word: str
581
+ :param synset: The synset for which we're building the relations.
582
+ :type synset: Synset
583
+ :param synset_relations: synset keys and relation types for which to display relations.
584
+ :type synset_relations: dict(synset_key, set(relation_type))
585
+ :return: The HTML for a synset's relations
586
+ :rtype: str
587
+ '''
588
+
589
+ if not synset.name() in synset_relations:
590
+ return ""
591
+ ref = Reference(word, synset_relations)
592
+
593
+ def relation_html(r):
594
+ if isinstance(r, Synset):
595
+ return make_lookup_link(Reference(r.lemma_names()[0]), r.lemma_names()[0])
596
+ elif isinstance(r, Lemma):
597
+ return relation_html(r.synset())
598
+ elif isinstance(r, tuple):
599
+ # It's probably a tuple containing a Synset and a list of
600
+ # similar tuples. This forms a tree of synsets.
601
+ return "%s\n<ul>%s</ul>\n" % \
602
+ (relation_html(r[0]),
603
+ ''.join('<li>%s</li>\n' % relation_html(sr) for sr in r[1]))
604
+ else:
605
+ raise TypeError("r must be a synset, lemma or list, it was: type(r) = %s, r = %s" % (type(r), r))
606
+
607
+ def make_synset_html(db_name, disp_name, rels):
608
+ synset_html = '<i>%s</i>\n' % \
609
+ make_lookup_link(
610
+ copy.deepcopy(ref).toggle_synset_relation(synset, db_name).encode(),
611
+ disp_name)
612
+
613
+ if db_name in ref.synset_relations[synset.name()]:
614
+ synset_html += '<ul>%s</ul>\n' % \
615
+ ''.join("<li>%s</li>\n" % relation_html(r) for r in rels)
616
+
617
+ return synset_html
618
+
619
+ html = '<ul>' + \
620
+ '\n'.join(("<li>%s</li>" % make_synset_html(*rel_data) for rel_data
621
+ in get_relations_data(word, synset)
622
+ if rel_data[2] != [])) + \
623
+ '</ul>'
624
+
625
+ return html
626
+
627
+
628
+ class Reference(object):
629
+ """
630
+ A reference to a page that may be generated by page_word
631
+ """
632
+
633
+ def __init__(self, word, synset_relations=dict()):
634
+ """
635
+ Build a reference to a new page.
636
+
637
+ word is the word or words (separated by commas) for which to
638
+ search for synsets of
639
+
640
+ synset_relations is a dictionary of synset keys to sets of
641
+ synset relation identifaiers to unfold a list of synset
642
+ relations for.
643
+ """
644
+ self.word = word
645
+ self.synset_relations = synset_relations
646
+
647
+ def encode(self):
648
+ """
649
+ Encode this reference into a string to be used in a URL.
650
+ """
651
+ # This uses a tuple rather than an object since the python
652
+ # pickle representation is much smaller and there is no need
653
+ # to represent the complete object.
654
+ string = pickle.dumps((self.word, self.synset_relations), -1)
655
+ return base64.urlsafe_b64encode(string).decode()
656
+
657
+ @staticmethod
658
+ def decode(string):
659
+ """
660
+ Decode a reference encoded with Reference.encode
661
+ """
662
+ string = base64.urlsafe_b64decode(string.encode())
663
+ word, synset_relations = pickle.loads(string)
664
+ return Reference(word, synset_relations)
665
+
666
+ def toggle_synset_relation(self, synset, relation):
667
+ """
668
+ Toggle the display of the relations for the given synset and
669
+ relation type.
670
+
671
+ This function will throw a KeyError if the synset is currently
672
+ not being displayed.
673
+ """
674
+ if relation in self.synset_relations[synset.name()]:
675
+ self.synset_relations[synset.name()].remove(relation)
676
+ else:
677
+ self.synset_relations[synset.name()].add(relation)
678
+
679
+ return self
680
+
681
+ def toggle_synset(self, synset):
682
+ """
683
+ Toggle displaying of the relation types for the given synset
684
+ """
685
+ if synset.name() in self.synset_relations:
686
+ del self.synset_relations[synset.name()]
687
+ else:
688
+ self.synset_relations[synset.name()] = set()
689
+
690
+ return self
691
+
692
+
693
+ def make_lookup_link(ref, label):
694
+ return '<a href="lookup_%s">%s</a>' % (ref.encode(), label)
695
+
696
+
697
+ def page_from_word(word):
698
+ """
699
+ Return a HTML page for the given word.
700
+
701
+ :type word: str
702
+ :param word: The currently active word
703
+ :return: A tuple (page,word), where page is the new current HTML page
704
+ to be sent to the browser and
705
+ word is the new current word
706
+ :rtype: A tuple (str,str)
707
+ """
708
+ return page_from_reference(Reference(word))
709
+
710
+ def page_from_href(href):
711
+ '''
712
+ Returns a tuple of the HTML page built and the new current word
713
+
714
+ :param href: The hypertext reference to be solved
715
+ :type href: str
716
+ :return: A tuple (page,word), where page is the new current HTML page
717
+ to be sent to the browser and
718
+ word is the new current word
719
+ :rtype: A tuple (str,str)
720
+ '''
721
+ return page_from_reference(Reference.decode(href))
722
+
723
+ def page_from_reference(href):
724
+ '''
725
+ Returns a tuple of the HTML page built and the new current word
726
+
727
+ :param href: The hypertext reference to be solved
728
+ :type href: str
729
+ :return: A tuple (page,word), where page is the new current HTML page
730
+ to be sent to the browser and
731
+ word is the new current word
732
+ :rtype: A tuple (str,str)
733
+ '''
734
+ word = href.word
735
+ pos_forms = defaultdict(list)
736
+ words = word.split(',')
737
+ words = [w for w in [w.strip().lower().replace(' ', '_')
738
+ for w in words]
739
+ if w != ""]
740
+ if len(words) == 0:
741
+ # No words were found.
742
+ return "", "Please specify a word to search for."
743
+
744
+ # This looks up multiple words at once. This is probably not
745
+ # necessary and may lead to problems.
746
+ for w in words:
747
+ for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]:
748
+ form = wn.morphy(w, pos)
749
+ if form and form not in pos_forms[pos]:
750
+ pos_forms[pos].append(form)
751
+ body = ''
752
+ for pos,pos_str,name in _pos_tuples():
753
+ if pos in pos_forms:
754
+ body += _hlev(3, name) + '\n'
755
+ for w in pos_forms[pos]:
756
+ # Not all words of exc files are in the database, skip
757
+ # to the next word if a KeyError is raised.
758
+ try:
759
+ body += _collect_all_synsets(w, pos, href.synset_relations)
760
+ except KeyError:
761
+ pass
762
+ if not body:
763
+ body = "The word or words '%s' where not found in the dictonary." % word
764
+ return body, word
765
+
766
+
767
+ #####################################################################
768
+ # Static pages
769
+ #####################################################################
770
+
771
+ def get_static_page_by_path(path):
772
+ """
773
+ Return a static HTML page from the path given.
774
+ """
775
+ if path == "index_2.html":
776
+ return get_static_index_page(False)
777
+ elif path == "index.html":
778
+ return get_static_index_page(True)
779
+ elif path == "NLTK Wordnet Browser Database Info.html":
780
+ return "Display of Wordnet Database Statistics is not supported"
781
+ elif path == "upper_2.html":
782
+ return get_static_upper_page(False)
783
+ elif path == "upper.html":
784
+ return get_static_upper_page(True)
785
+ elif path == "web_help.html":
786
+ return get_static_web_help_page()
787
+ elif path == "wx_help.html":
788
+ return get_static_wx_help_page()
789
+ else:
790
+ return "Internal error: Path for static page '%s' is unknown" % path
791
+
792
+
793
+ def get_static_web_help_page():
794
+ """
795
+ Return the static web help page.
796
+ """
797
+ return \
798
+ """
799
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
800
+ <html>
801
+ <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
802
+ Copyright (C) 2001-2018 NLTK Project
803
+ Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
804
+ URL: <http://nltk.org/>
805
+ For license information, see LICENSE.TXT -->
806
+ <head>
807
+ <meta http-equiv='Content-Type' content='text/html; charset=us-ascii'>
808
+ <title>NLTK Wordnet Browser display of: * Help *</title>
809
+ </head>
810
+ <body bgcolor='#F5F5F5' text='#000000'>
811
+ <h2>NLTK Wordnet Browser Help</h2>
812
+ <p>The NLTK Wordnet Browser is a tool to use in browsing the Wordnet database. It tries to behave like the Wordnet project's web browser but the difference is that the NLTK Wordnet Browser uses a local Wordnet database.
813
+ <p><b>You are using the Javascript client part of the NLTK Wordnet BrowseServer.</b> We assume your browser is in tab sheets enabled mode.</p>
814
+ <p>For background information on Wordnet, see the Wordnet project home page: <a href="http://wordnet.princeton.edu/"><b> http://wordnet.princeton.edu/</b></a>. For more information on the NLTK project, see the project home:
815
+ <a href="http://nltk.sourceforge.net/"><b>http://nltk.sourceforge.net/</b></a>. To get an idea of what the Wordnet version used by this browser includes choose <b>Show Database Info</b> from the <b>View</b> submenu.</p>
816
+ <h3>Word search</h3>
817
+ <p>The word to be searched is typed into the <b>New Word</b> field and the search started with Enter or by clicking the <b>Search</b> button. There is no uppercase/lowercase distinction: the search word is transformed to lowercase before the search.</p>
818
+ <p>In addition, the word does not have to be in base form. The browser tries to find the possible base form(s) by making certain morphological substitutions. Typing <b>fLIeS</b> as an obscure example gives one <a href="MfLIeS">this</a>. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination.</p>
819
+ <p>The result of a search is a display of one or more
820
+ <b>synsets</b> for every part of speech in which a form of the
821
+ search word was found to occur. A synset is a set of words
822
+ having the same sense or meaning. Each word in a synset that is
823
+ underlined is a hyperlink which can be clicked to trigger an
824
+ automatic search for that word.</p>
825
+ <p>Every synset has a hyperlink <b>S:</b> at the start of its
826
+ display line. Clicking that symbol shows you the name of every
827
+ <b>relation</b> that this synset is part of. Every relation name is a hyperlink that opens up a display for that relation. Clicking it another time closes the display again. Clicking another relation name on a line that has an opened relation closes the open relation and opens the clicked relation.</p>
828
+ <p>It is also possible to give two or more words or collocations to be searched at the same time separating them with a comma like this <a href="Mcheer up,clear up">cheer up,clear up</a>, for example. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination. As you could see the search result includes the synsets found in the same order than the forms were given in the search field.</p>
829
+ <p>
830
+ There are also word level (lexical) relations recorded in the Wordnet database. Opening this kind of relation displays lines with a hyperlink <b>W:</b> at their beginning. Clicking this link shows more info on the word in question.</p>
831
+ <h3>The Buttons</h3>
832
+ <p>The <b>Search</b> and <b>Help</b> buttons need no more explanation. </p>
833
+ <p>The <b>Show Database Info</b> button shows a collection of Wordnet database statistics.</p>
834
+ <p>The <b>Shutdown the Server</b> button is shown for the first client of the BrowServer program i.e. for the client that is automatically launched when the BrowServer is started but not for the succeeding clients in order to protect the server from accidental shutdowns.
835
+ </p></body>
836
+ </html>
837
+ """
838
+
839
+
840
+ def get_static_welcome_message():
841
+ """
842
+ Get the static welcome page.
843
+ """
844
+ return \
845
+ """
846
+ <h3>Search Help</h3>
847
+ <ul><li>The display below the line is an example of the output the browser
848
+ shows you when you enter a search word. The search word was <b>green</b>.</li>
849
+ <li>The search result shows for different parts of speech the <b>synsets</b>
850
+ i.e. different meanings for the word.</li>
851
+ <li>All underlined texts are hypertext links. There are two types of links:
852
+ word links and others. Clicking a word link carries out a search for the word
853
+ in the Wordnet database.</li>
854
+ <li>Clicking a link of the other type opens a display section of data attached
855
+ to that link. Clicking that link a second time closes the section again.</li>
856
+ <li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
857
+ <li>Clicking on a relation name opens a section that displays the associated
858
+ synsets.</li>
859
+ <li>Type a search word in the <b>Next Word</b> field and start the search by the
860
+ <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
861
+ </ul>
862
+ """
863
+
864
+ def get_static_index_page(with_shutdown):
865
+ """
866
+ Get the static index page.
867
+ """
868
+ template = \
869
+ """
870
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
871
+ <HTML>
872
+ <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
873
+ Copyright (C) 2001-2018 NLTK Project
874
+ Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
875
+ URL: <http://nltk.org/>
876
+ For license information, see LICENSE.TXT -->
877
+ <HEAD>
878
+ <TITLE>NLTK Wordnet Browser</TITLE>
879
+ </HEAD>
880
+
881
+ <frameset rows="7%%,93%%">
882
+ <frame src="%s" name="header">
883
+ <frame src="start_page" name="body">
884
+ </frameset>
885
+ </HTML>
886
+ """
887
+ if with_shutdown:
888
+ upper_link = "upper.html"
889
+ else:
890
+ upper_link = "upper_2.html"
891
+
892
+ return template % upper_link
893
+
894
+
895
+ def get_static_upper_page(with_shutdown):
896
+ """
897
+ Return the upper frame page,
898
+
899
+ If with_shutdown is True then a 'shutdown' button is also provided
900
+ to shutdown the server.
901
+ """
902
+ template = \
903
+ """
904
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
905
+ <html>
906
+ <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
907
+ Copyright (C) 2001-2018 NLTK Project
908
+ Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
909
+ URL: <http://nltk.org/>
910
+ For license information, see LICENSE.TXT -->
911
+ <head>
912
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
913
+ <title>Untitled Document</title>
914
+ </head>
915
+ <body>
916
+ <form method="GET" action="search" target="body">
917
+ Current Word:&nbsp;<input type="text" id="currentWord" size="10" disabled>
918
+ Next Word:&nbsp;<input type="text" id="nextWord" name="nextWord" size="10">
919
+ <input name="searchButton" type="submit" value="Search">
920
+ </form>
921
+ <a target="body" href="web_help.html">Help</a>
922
+ %s
923
+
924
+ </body>
925
+ </html>
926
+ """
927
+ if with_shutdown:
928
+ shutdown_link = "<a href=\"SHUTDOWN THE SERVER\">Shutdown</a>"
929
+ else:
930
+ shutdown_link = ""
931
+
932
+ return template % shutdown_link
933
+
934
+
935
+
936
+ def usage():
937
+ """
938
+ Display the command line help message.
939
+ """
940
+ print(__doc__)
941
+
942
+ def app():
943
+ # Parse and interpret options.
944
+ (opts, _) = getopt.getopt(argv[1:], "l:p:sh",
945
+ ["logfile=", "port=", "server-mode", "help"])
946
+ port = 8000
947
+ server_mode = False
948
+ help_mode = False
949
+ logfilename = None
950
+ for (opt, value) in opts:
951
+ if (opt == "-l") or (opt == "--logfile"):
952
+ logfilename = str(value)
953
+ elif (opt == "-p") or (opt == "--port"):
954
+ port = int(value)
955
+ elif (opt == "-s") or (opt == "--server-mode"):
956
+ server_mode = True
957
+ elif (opt == "-h") or (opt == "--help"):
958
+ help_mode = True
959
+
960
+ if help_mode:
961
+ usage()
962
+ else:
963
+ wnb(port, not server_mode, logfilename)
964
+
965
+ if __name__ == '__main__':
966
+ app()
967
+
968
+ __all__ = ['app']