├── LICENSE ├── README.md ├── clean_np.py ├── docopt.py ├── senna.py ├── stanford.py └── test.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nltk_cli 2 | 3 | This repo contains the **TL;DR** solutions to using third-party tools 4 | (e.g. Stanford NLP, SENNA NLP, etc.) with NLTK. 5 | 6 | **Disclaimers**: It comes with unexpected caveats that are idiosyncratic to (i) the data you are processing and (ii) how NLTK API and Stanford NLP tools work. 7 | 8 | Installation 9 | ==== 10 | 11 | ```bash 12 | cd $HOME 13 | 14 | # Download the Stanford NLP tools 15 | wget http://nlp.stanford.edu/software/stanford-ner-2015-04-20.zip 16 | wget http://nlp.stanford.edu/software/stanford-postagger-full-2015-04-20.zip 17 | wget http://nlp.stanford.edu/software/stanford-parser-full-2015-04-20.zip 18 | # Extract the zip file. 19 | unzip stanford-ner-2015-04-20.zip 20 | unzip stanford-parser-full-2015-04-20.zip 21 | unzip stanford-postagger-full-2015-04-20.zip 22 | # Change to a shorter path. 23 | mv stanford-postagger-full-2015-04-20 stanford-postagger 24 | mv stanford-parser-full-2015-04-20 stanford-parser 25 | mv stanford-ner-2015-04-20 stanford-ner 26 | 27 | # Download the Stanford Spanish models. 28 | wget http://nlp.stanford.edu/software/stanford-spanish-corenlp-2015-01-08-models.jar 29 | unzip stanford-spanish-corenlp-2015-01-08-models.jar -d stanford-spanish 30 | cp stanford-spanish/edu/stanford/nlp/models/ner/* stanford-ner/classifiers/ 31 | 32 | # Download the Stanford German models. 33 | wget http://nlp.stanford.edu/software/stanford-german-2015-01-30-models.jar 34 | unzip stanford-german-2015-01-30-models.jar -d stanford-german 35 | cp stanford-german/edu/stanford/nlp/models/ner/* stanford-ner/classifiers/ 36 | 37 | # Download the Stanford Chinese models. 38 | wget http://nlp.stanford.edu/software/stanford-chinese-corenlp-2015-04-20-models.jar 39 | unzip stanford-chinese-corenlp-2015-04-20-models.jar -d stanford-chinese-ner 40 | cp stanford-chinese-ner/edu/stanford/nlp/models/ner/* stanford-ner/classifiers/ 41 | 42 | # Download the SENNA tools. 43 | wget http://ronan.collobert.com/senna/senna-v3.0.tgz 44 | tar zxvf senna-v3.0.tgz 45 | mv senna-v3.0 senna 46 | 47 | # Install NLTK 48 | pip install -U nltk 49 | # Git clone this repository. 50 | git clone https://github.com/alvations/nltk_cli.git 51 | ``` 52 | 53 | Usage 54 | ==== 55 | 56 | ```bash 57 | cd nltk_cli 58 | 59 | ############################################################################### 60 | # Stanford NLP Tools 61 | ############################################################################### 62 | 63 | # Using Stanford LexParser 64 | python3 stanford.py --tool=lexparser \ 65 | --jar=$HOME/stanford-parser/stanford-parser.jar \ 66 | --modeljar=$HOME/stanford-parser/stanford-parser-3.5.2-models.jar \ 67 | --model=edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz \ 68 | --input=test.txt 69 | 70 | # Using Stanford POSTagger 71 | python3 stanford.py --tool=postagger \ 72 | --jar=$HOME/stanford-postagger/stanford-postagger.jar \ 73 | --model=$HOME/stanford-postagger/models/english-bidirectional-distsim.tagger \ 74 | --input=test.txt 75 | 76 | # Using Stanford NERTagger 77 | python3 stanford.py --tool=nertagger \ 78 | --jar=$HOME/stanford-ner/stanford-ner.jar \ 79 | --model=$HOME/stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz \ 80 | --input=test.txt 81 | 82 | # TL;DR way to use Stanford LexParser, make sure your `stanford-parser` directory 83 | # is in your $HOME directory and you have installed as per the installation 84 | # instruction above, otherwise these TL;DR commands won't work. 85 | python3 stanford.py --postag test.txt 86 | python3 stanford.py --nertag test.txt 87 | python3 stanford.py --lexparser test.txt 88 | 89 | # TL;DR with model option. 90 | python3 stanford.py --lexparse test.txt \ 91 | --model=edu/stanford/nlp/models/lexparser/wsjPCFG.ser.gz 92 | python3 stanford.py --postag test.txt \ 93 | --model=$HOME/stanford-postagger/models/english-bidirectional-distsim.tagger 94 | python3 stanford.py --nertag test.txt \ 95 | --model=$HOME/stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz 96 | 97 | ############################################################################### 98 | # SENNA NLP Tools 99 | ############################################################################### 100 | 101 | # Using SENNA POSTagger. 102 | python senna.py --sennadir $HOME/senna --postag --input test.txt 103 | 104 | # Using SENNA NERTagger. 105 | python senna.py --sennadir $HOME/senna --nertag --input test.txt 106 | 107 | # Using SENNA ChunkTagger. 108 | python senna.py --sennadir $HOME/senna --chunktag --input test.txt 109 | 110 | # TL;DR NP Chunk Extractor using SENNA ChunkTagger. 111 | python senna.py --sennadir $HOME/senna --chunk NP test.txt 112 | python senna.py --sennadir $HOME/senna --np test.txt 113 | 114 | # Tl;DR way to use SENNA Taggers, make sure your `senna` directory is in your 115 | # $HOME directory and you have installed as per the installation instruction 116 | # above, otherwise, these Tl;DR might not work. 117 | python senna.py --postag --input test.txt 118 | python senna.py --nertag --input test.txt 119 | python senna.py --chunktag --input test.txt 120 | 121 | # Tl;DR way to use SENNA ChunkTagger to extract NPs, make sure your `senna` 122 | # directory is in your $HOME directory and you have installed as per the 123 | # installation instruction above, otherwise, these Tl;DR might not work. 124 | python senna.py --np test.txt 125 | python senna.py --vp test.txt 126 | python senna.py --chunk NP test.txt 127 | python senna.py --chunk VP test.txt 128 | 129 | ############################################################################## 130 | # Terminator Term Extract filters. 131 | ############################################################################## 132 | 133 | # Extracts NPs using SENNA ChunkTagger. 134 | python3 senna.py --np test.txt --output test.np 135 | # Filter NPs using Terminator semi-rule based cleaner. Input can be either 136 | # one NP per line or multiple NPs per line separated by pipe, i.e. "|" 137 | python3 clean_np.py test.np 138 | # If you would like to output the filtered NPs: 139 | python3 clean_np.py test.np --output test.filtered.np 140 | # To remove empty lines from the filtered NPs list: 141 | python3 clean_np.py test.np | sed '/^$/d' 142 | # To get unique list of NPs 143 | python3 clean_np.py test.np | sed '/^$/d' | sort | uniq 144 | ``` 145 | 146 | Note: The `test.txt` file is the `fish-head-curry` file from the [NTU-Multilingual Corpus](http://compling.hss.ntu.edu.sg/ntumc/) 147 | 148 | FAQ 149 | ==== 150 | 151 | **UnicodeEncodeError: 'ascii' codec can't encode character...** 152 | 153 | 154 | If any of your output from the commands above cannot be output using `>`, e.g. 155 | 156 | ```bash 157 | $ python senna.py --np test.txt > test.np 158 | Traceback (most recent call last): 159 | File "senna.py", line 114, in 160 | print(processed_sent) 161 | UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 9: ordinal not in range(128) 162 | ``` 163 | 164 | Then try the `--output` parameter, e.g.: 165 | 166 | ```bash 167 | $ python senna.py --np test.txt --output test.np 168 | ``` 169 | 170 | Alternatively, you can set your STDOUT encoding, e.g.: 171 | 172 | ```bash 173 | $ export PYTHONIOENCODING=utf-8 174 | $ python senna.py --np test.txt > test.np 175 | ``` 176 | 177 | ---- 178 | 179 | **IndexError: Misalignment error occurred at sentence number ...** 180 | 181 | If you get an error as such: 182 | 183 | ```bash 184 | $ python senna.py --np test.txt --output test.np 185 | Traceback (most recent call last): 186 | File "senna.py", line 110, in 187 | for processed_sent in process(sentences, tool, arguments['--chunk']): 188 | File "senna.py", line 83, in senna_extract_chunks 189 | tagged_sents = chunker.tag_sents(sentences) 190 | File "/usr/local/lib/python2.7/dist-packages/nltk/tag/senna.py", line 70, in tag_sents 191 | tagged_sents = super(SennaChunkTagger, self).tag_sents(sentences) 192 | File "/usr/local/lib/python2.7/dist-packages/nltk/classify/senna.py", line 167, in tag_sents 193 | % sentence_index) 194 | IndexError: Misalignment error occurred at sentence number 11. Possible reason is that the sentence size exceeded the maximum size. Check the documentation of Senna class for more information. 195 | ``` 196 | 197 | First check that you have no empty lines in your input file, then remove the empty line, you can also do: 198 | 199 | ```bash 200 | $ sed '/^$/d' test.txt > test.noempty.txt 201 | $ python senna.py --np test.noempty.txt --output test.np 202 | ``` 203 | -------------------------------------------------------------------------------- /clean_np.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -*- coding: utf-8 -*- 2 | 3 | """ 4 | This script takes an output from: 5 | 6 | python3 nltk_cli/senna.py --np test.txt > test.np 7 | 8 | And process the noun phrases to filter out phrases 9 | 10 | (i) that don't have the last word tagged as NN 11 | (ii) has any token that is a stopword 12 | (iii) the first and last word in phrase is not a punctuation 13 | 14 | This is part of the Terminator software from 15 | https://github.com/alvations/Terminator (Tan, 2015) 16 | 17 | Usage: 18 | 19 | python3 nltk_cli/clean_np.py test.np --output test.filtered.np 20 | 21 | Reference: 22 | 23 | Liling Tan. 2015. EXPERT Innovations in Terminology Extraction and 24 | Ontology Induction. In Proceedings of Proceedings of the EXPERT Scientific 25 | and Technological Workshop. Malaga, Spain. 26 | """ 27 | 28 | import io, sys 29 | from os.path import expanduser 30 | from string import punctuation 31 | 32 | from nltk.util import ngrams 33 | from nltk.corpus import stopwords 34 | from nltk import word_tokenize 35 | from nltk.tag import PerceptronTagger 36 | 37 | tagger = PerceptronTagger() 38 | pos_tag = tagger.tag 39 | STOPWORDS = stopwords.words('english') 40 | 41 | def simple_filter(list_of_ngrams): 42 | return [ng for ng in list_of_ngrams if 43 | ng.lower() not in STOPWORDS and 44 | ng[0] not in punctuation and ng[-1] not in punctuation and 45 | ng.split()[-1].lower() not in STOPWORDS and 46 | ng.split()[0].lower() not in STOPWORDS and 47 | not any(i for i in ng.split() if i.lower() in STOPWORDS) and 48 | any(pos for word,pos in pos_tag(ng.lower().split()) 49 | if pos.startswith('NN')) and 50 | ')' not in ng and '(' not in ng and ',' not in ng and 51 | 'pinyin' not in ng and 52 | ng.split()[0] not in ['more', 'less']] 53 | 54 | outfile = "" 55 | 56 | try: 57 | if sys.argv[2] == '--output': 58 | outfile = sys.argv[3] 59 | fout = io.open(outfile, 'w', encoding='utf8') 60 | except IndexError: 61 | pass 62 | 63 | with io.open(sys.argv[1], 'r', encoding='utf8') as fin: 64 | for line in fin: 65 | list_of_ngrams = line.split('\t')[0].split('|') 66 | for ng in simple_filter(list_of_ngrams): 67 | if outfile: 68 | fout.write(ng + '\n') 69 | else: 70 | print(ng) 71 | 72 | 73 | -------------------------------------------------------------------------------- /docopt.py: -------------------------------------------------------------------------------- 1 | """Pythonic command-line interface parser that will make you smile. 2 | 3 | * http://docopt.org 4 | * Repository and issue-tracker: https://github.com/docopt/docopt 5 | * Licensed under terms of MIT license (see LICENSE-MIT) 6 | * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com 7 | 8 | """ 9 | import sys 10 | import re 11 | 12 | 13 | __all__ = ['docopt'] 14 | __version__ = '0.6.1' 15 | 16 | 17 | class DocoptLanguageError(Exception): 18 | 19 | """Error in construction of usage-message by developer.""" 20 | 21 | 22 | class DocoptExit(SystemExit): 23 | 24 | """Exit in case user invoked program with incorrect arguments.""" 25 | 26 | usage = '' 27 | 28 | def __init__(self, message=''): 29 | SystemExit.__init__(self, (message + '\n' + self.usage).strip()) 30 | 31 | 32 | class Pattern(object): 33 | 34 | def __eq__(self, other): 35 | return repr(self) == repr(other) 36 | 37 | def __hash__(self): 38 | return hash(repr(self)) 39 | 40 | def fix(self): 41 | self.fix_identities() 42 | self.fix_repeating_arguments() 43 | return self 44 | 45 | def fix_identities(self, uniq=None): 46 | """Make pattern-tree tips point to same object if they are equal.""" 47 | if not hasattr(self, 'children'): 48 | return self 49 | uniq = list(set(self.flat())) if uniq is None else uniq 50 | for i, child in enumerate(self.children): 51 | if not hasattr(child, 'children'): 52 | assert child in uniq 53 | self.children[i] = uniq[uniq.index(child)] 54 | else: 55 | child.fix_identities(uniq) 56 | 57 | def fix_repeating_arguments(self): 58 | """Fix elements that should accumulate/increment values.""" 59 | either = [list(child.children) for child in transform(self).children] 60 | for case in either: 61 | for e in [child for child in case if case.count(child) > 1]: 62 | if type(e) is Argument or type(e) is Option and e.argcount: 63 | if e.value is None: 64 | e.value = [] 65 | elif type(e.value) is not list: 66 | e.value = e.value.split() 67 | if type(e) is Command or type(e) is Option and e.argcount == 0: 68 | e.value = 0 69 | return self 70 | 71 | 72 | def transform(pattern): 73 | """Expand pattern into an (almost) equivalent one, but with single Either. 74 | 75 | Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) 76 | Quirks: [-a] => (-a), (-a...) => (-a -a) 77 | 78 | """ 79 | result = [] 80 | groups = [[pattern]] 81 | while groups: 82 | children = groups.pop(0) 83 | parents = [Required, Optional, OptionsShortcut, Either, OneOrMore] 84 | if any(t in map(type, children) for t in parents): 85 | child = [c for c in children if type(c) in parents][0] 86 | children.remove(child) 87 | if type(child) is Either: 88 | for c in child.children: 89 | groups.append([c] + children) 90 | elif type(child) is OneOrMore: 91 | groups.append(child.children * 2 + children) 92 | else: 93 | groups.append(child.children + children) 94 | else: 95 | result.append(children) 96 | return Either(*[Required(*e) for e in result]) 97 | 98 | 99 | class LeafPattern(Pattern): 100 | 101 | """Leaf/terminal node of a pattern tree.""" 102 | 103 | def __init__(self, name, value=None): 104 | self.name, self.value = name, value 105 | 106 | def __repr__(self): 107 | return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value) 108 | 109 | def flat(self, *types): 110 | return [self] if not types or type(self) in types else [] 111 | 112 | def match(self, left, collected=None): 113 | collected = [] if collected is None else collected 114 | pos, match = self.single_match(left) 115 | if match is None: 116 | return False, left, collected 117 | left_ = left[:pos] + left[pos + 1:] 118 | same_name = [a for a in collected if a.name == self.name] 119 | if type(self.value) in (int, list): 120 | if type(self.value) is int: 121 | increment = 1 122 | else: 123 | increment = ([match.value] if type(match.value) is str 124 | else match.value) 125 | if not same_name: 126 | match.value = increment 127 | return True, left_, collected + [match] 128 | same_name[0].value += increment 129 | return True, left_, collected 130 | return True, left_, collected + [match] 131 | 132 | 133 | class BranchPattern(Pattern): 134 | 135 | """Branch/inner node of a pattern tree.""" 136 | 137 | def __init__(self, *children): 138 | self.children = list(children) 139 | 140 | def __repr__(self): 141 | return '%s(%s)' % (self.__class__.__name__, 142 | ', '.join(repr(a) for a in self.children)) 143 | 144 | def flat(self, *types): 145 | if type(self) in types: 146 | return [self] 147 | return sum([child.flat(*types) for child in self.children], []) 148 | 149 | 150 | class Argument(LeafPattern): 151 | 152 | def single_match(self, left): 153 | for n, pattern in enumerate(left): 154 | if type(pattern) is Argument: 155 | return n, Argument(self.name, pattern.value) 156 | return None, None 157 | 158 | @classmethod 159 | def parse(class_, source): 160 | name = re.findall('(<\S*?>)', source)[0] 161 | value = re.findall('\[default: (.*)\]', source, flags=re.I) 162 | return class_(name, value[0] if value else None) 163 | 164 | 165 | class Command(Argument): 166 | 167 | def __init__(self, name, value=False): 168 | self.name, self.value = name, value 169 | 170 | def single_match(self, left): 171 | for n, pattern in enumerate(left): 172 | if type(pattern) is Argument: 173 | if pattern.value == self.name: 174 | return n, Command(self.name, True) 175 | else: 176 | break 177 | return None, None 178 | 179 | 180 | class Option(LeafPattern): 181 | 182 | def __init__(self, short=None, long=None, argcount=0, value=False): 183 | assert argcount in (0, 1) 184 | self.short, self.long, self.argcount = short, long, argcount 185 | self.value = None if value is False and argcount else value 186 | 187 | @classmethod 188 | def parse(class_, option_description): 189 | short, long, argcount, value = None, None, 0, False 190 | options, _, description = option_description.strip().partition(' ') 191 | options = options.replace(',', ' ').replace('=', ' ') 192 | for s in options.split(): 193 | if s.startswith('--'): 194 | long = s 195 | elif s.startswith('-'): 196 | short = s 197 | else: 198 | argcount = 1 199 | if argcount: 200 | matched = re.findall('\[default: (.*)\]', description, flags=re.I) 201 | value = matched[0] if matched else None 202 | return class_(short, long, argcount, value) 203 | 204 | def single_match(self, left): 205 | for n, pattern in enumerate(left): 206 | if self.name == pattern.name: 207 | return n, pattern 208 | return None, None 209 | 210 | @property 211 | def name(self): 212 | return self.long or self.short 213 | 214 | def __repr__(self): 215 | return 'Option(%r, %r, %r, %r)' % (self.short, self.long, 216 | self.argcount, self.value) 217 | 218 | 219 | class Required(BranchPattern): 220 | 221 | def match(self, left, collected=None): 222 | collected = [] if collected is None else collected 223 | l = left 224 | c = collected 225 | for pattern in self.children: 226 | matched, l, c = pattern.match(l, c) 227 | if not matched: 228 | return False, left, collected 229 | return True, l, c 230 | 231 | 232 | class Optional(BranchPattern): 233 | 234 | def match(self, left, collected=None): 235 | collected = [] if collected is None else collected 236 | for pattern in self.children: 237 | m, left, collected = pattern.match(left, collected) 238 | return True, left, collected 239 | 240 | 241 | class OptionsShortcut(Optional): 242 | 243 | """Marker/placeholder for [options] shortcut.""" 244 | 245 | 246 | class OneOrMore(BranchPattern): 247 | 248 | def match(self, left, collected=None): 249 | assert len(self.children) == 1 250 | collected = [] if collected is None else collected 251 | l = left 252 | c = collected 253 | l_ = None 254 | matched = True 255 | times = 0 256 | while matched: 257 | # could it be that something didn't match but changed l or c? 258 | matched, l, c = self.children[0].match(l, c) 259 | times += 1 if matched else 0 260 | if l_ == l: 261 | break 262 | l_ = l 263 | if times >= 1: 264 | return True, l, c 265 | return False, left, collected 266 | 267 | 268 | class Either(BranchPattern): 269 | 270 | def match(self, left, collected=None): 271 | collected = [] if collected is None else collected 272 | outcomes = [] 273 | for pattern in self.children: 274 | matched, _, _ = outcome = pattern.match(left, collected) 275 | if matched: 276 | outcomes.append(outcome) 277 | if outcomes: 278 | return min(outcomes, key=lambda outcome: len(outcome[1])) 279 | return False, left, collected 280 | 281 | 282 | class Tokens(list): 283 | 284 | def __init__(self, source, error=DocoptExit): 285 | self += source.split() if hasattr(source, 'split') else source 286 | self.error = error 287 | 288 | @staticmethod 289 | def from_pattern(source): 290 | source = re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source) 291 | source = [s for s in re.split('\s+|(\S*<.*?>)', source) if s] 292 | return Tokens(source, error=DocoptLanguageError) 293 | 294 | def move(self): 295 | return self.pop(0) if len(self) else None 296 | 297 | def current(self): 298 | return self[0] if len(self) else None 299 | 300 | 301 | def parse_long(tokens, options): 302 | """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;""" 303 | long, eq, value = tokens.move().partition('=') 304 | assert long.startswith('--') 305 | value = None if eq == value == '' else value 306 | similar = [o for o in options if o.long == long] 307 | if tokens.error is DocoptExit and similar == []: # if no exact match 308 | similar = [o for o in options if o.long and o.long.startswith(long)] 309 | if len(similar) > 1: # might be simply specified ambiguously 2+ times? 310 | raise tokens.error('%s is not a unique prefix: %s?' % 311 | (long, ', '.join(o.long for o in similar))) 312 | elif len(similar) < 1: 313 | argcount = 1 if eq == '=' else 0 314 | o = Option(None, long, argcount) 315 | options.append(o) 316 | if tokens.error is DocoptExit: 317 | o = Option(None, long, argcount, value if argcount else True) 318 | else: 319 | o = Option(similar[0].short, similar[0].long, 320 | similar[0].argcount, similar[0].value) 321 | if o.argcount == 0: 322 | if value is not None: 323 | raise tokens.error('%s must not have an argument' % o.long) 324 | else: 325 | if value is None: 326 | if tokens.current() in [None, '--']: 327 | raise tokens.error('%s requires argument' % o.long) 328 | value = tokens.move() 329 | if tokens.error is DocoptExit: 330 | o.value = value if value is not None else True 331 | return [o] 332 | 333 | 334 | def parse_shorts(tokens, options): 335 | """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;""" 336 | token = tokens.move() 337 | assert token.startswith('-') and not token.startswith('--') 338 | left = token.lstrip('-') 339 | parsed = [] 340 | while left != '': 341 | short, left = '-' + left[0], left[1:] 342 | similar = [o for o in options if o.short == short] 343 | if len(similar) > 1: 344 | raise tokens.error('%s is specified ambiguously %d times' % 345 | (short, len(similar))) 346 | elif len(similar) < 1: 347 | o = Option(short, None, 0) 348 | options.append(o) 349 | if tokens.error is DocoptExit: 350 | o = Option(short, None, 0, True) 351 | else: # why copying is necessary here? 352 | o = Option(short, similar[0].long, 353 | similar[0].argcount, similar[0].value) 354 | value = None 355 | if o.argcount != 0: 356 | if left == '': 357 | if tokens.current() in [None, '--']: 358 | raise tokens.error('%s requires argument' % short) 359 | value = tokens.move() 360 | else: 361 | value = left 362 | left = '' 363 | if tokens.error is DocoptExit: 364 | o.value = value if value is not None else True 365 | parsed.append(o) 366 | return parsed 367 | 368 | 369 | def parse_pattern(source, options): 370 | tokens = Tokens.from_pattern(source) 371 | result = parse_expr(tokens, options) 372 | if tokens.current() is not None: 373 | raise tokens.error('unexpected ending: %r' % ' '.join(tokens)) 374 | return Required(*result) 375 | 376 | 377 | def parse_expr(tokens, options): 378 | """expr ::= seq ( '|' seq )* ;""" 379 | seq = parse_seq(tokens, options) 380 | if tokens.current() != '|': 381 | return seq 382 | result = [Required(*seq)] if len(seq) > 1 else seq 383 | while tokens.current() == '|': 384 | tokens.move() 385 | seq = parse_seq(tokens, options) 386 | result += [Required(*seq)] if len(seq) > 1 else seq 387 | return [Either(*result)] if len(result) > 1 else result 388 | 389 | 390 | def parse_seq(tokens, options): 391 | """seq ::= ( atom [ '...' ] )* ;""" 392 | result = [] 393 | while tokens.current() not in [None, ']', ')', '|']: 394 | atom = parse_atom(tokens, options) 395 | if tokens.current() == '...': 396 | atom = [OneOrMore(*atom)] 397 | tokens.move() 398 | result += atom 399 | return result 400 | 401 | 402 | def parse_atom(tokens, options): 403 | """atom ::= '(' expr ')' | '[' expr ']' | 'options' 404 | | long | shorts | argument | command ; 405 | """ 406 | token = tokens.current() 407 | result = [] 408 | if token in '([': 409 | tokens.move() 410 | matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token] 411 | result = pattern(*parse_expr(tokens, options)) 412 | if tokens.move() != matching: 413 | raise tokens.error("unmatched '%s'" % token) 414 | return [result] 415 | elif token == 'options': 416 | tokens.move() 417 | return [OptionsShortcut()] 418 | elif token.startswith('--') and token != '--': 419 | return parse_long(tokens, options) 420 | elif token.startswith('-') and token not in ('-', '--'): 421 | return parse_shorts(tokens, options) 422 | elif token.startswith('<') and token.endswith('>') or token.isupper(): 423 | return [Argument(tokens.move())] 424 | else: 425 | return [Command(tokens.move())] 426 | 427 | 428 | def parse_argv(tokens, options, options_first=False): 429 | """Parse command-line argument vector. 430 | 431 | If options_first: 432 | argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; 433 | else: 434 | argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; 435 | 436 | """ 437 | parsed = [] 438 | while tokens.current() is not None: 439 | if tokens.current() == '--': 440 | return parsed + [Argument(None, v) for v in tokens] 441 | elif tokens.current().startswith('--'): 442 | parsed += parse_long(tokens, options) 443 | elif tokens.current().startswith('-') and tokens.current() != '-': 444 | parsed += parse_shorts(tokens, options) 445 | elif options_first: 446 | return parsed + [Argument(None, v) for v in tokens] 447 | else: 448 | parsed.append(Argument(None, tokens.move())) 449 | return parsed 450 | 451 | 452 | def parse_defaults(doc): 453 | defaults = [] 454 | for s in parse_section('options:', doc): 455 | # FIXME corner case "bla: options: --foo" 456 | _, _, s = s.partition(':') # get rid of "options:" 457 | split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:] 458 | split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])] 459 | options = [Option.parse(s) for s in split if s.startswith('-')] 460 | defaults += options 461 | return defaults 462 | 463 | 464 | def parse_section(name, source): 465 | pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)', 466 | re.IGNORECASE | re.MULTILINE) 467 | return [s.strip() for s in pattern.findall(source)] 468 | 469 | 470 | def formal_usage(section): 471 | _, _, section = section.partition(':') # drop "usage:" 472 | pu = section.split() 473 | return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )' 474 | 475 | 476 | def extras(help, version, options, doc): 477 | if help and any((o.name in ('-h', '--help')) and o.value for o in options): 478 | print(doc.strip("\n")) 479 | sys.exit() 480 | if version and any(o.name == '--version' and o.value for o in options): 481 | print(version) 482 | sys.exit() 483 | 484 | 485 | class Dict(dict): 486 | def __repr__(self): 487 | return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items())) 488 | 489 | 490 | def docopt(doc, argv=None, help=True, version=None, options_first=False): 491 | """Parse `argv` based on command-line interface described in `doc`. 492 | 493 | `docopt` creates your command-line interface based on its 494 | description that you pass as `doc`. Such description can contain 495 | --options, , commands, which could be 496 | [optional], (required), (mutually | exclusive) or repeated... 497 | 498 | Parameters 499 | ---------- 500 | doc : str 501 | Description of your command-line interface. 502 | argv : list of str, optional 503 | Argument vector to be parsed. sys.argv[1:] is used if not 504 | provided. 505 | help : bool (default: True) 506 | Set to False to disable automatic help on -h or --help 507 | options. 508 | version : any object 509 | If passed, the object will be printed if --version is in 510 | `argv`. 511 | options_first : bool (default: False) 512 | Set to True to require options precede positional arguments, 513 | i.e. to forbid options and positional arguments intermix. 514 | 515 | Returns 516 | ------- 517 | args : dict 518 | A dictionary, where keys are names of command-line elements 519 | such as e.g. "--verbose" and "", and values are the 520 | parsed values of those elements. 521 | 522 | Example 523 | ------- 524 | >>> from docopt import docopt 525 | >>> doc = ''' 526 | ... Usage: 527 | ... my_program tcp [--timeout=] 528 | ... my_program serial [--baud=] [--timeout=] 529 | ... my_program (-h | --help | --version) 530 | ... 531 | ... Options: 532 | ... -h, --help Show this screen and exit. 533 | ... --baud= Baudrate [default: 9600] 534 | ... ''' 535 | >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30'] 536 | >>> docopt(doc, argv) 537 | {'--baud': '9600', 538 | '--help': False, 539 | '--timeout': '30', 540 | '--version': False, 541 | '': '127.0.0.1', 542 | '': '80', 543 | 'serial': False, 544 | 'tcp': True} 545 | 546 | See also 547 | -------- 548 | * For video introduction see http://docopt.org 549 | * Full documentation is available in README.rst as well as online 550 | at https://github.com/docopt/docopt#readme 551 | 552 | """ 553 | argv = sys.argv[1:] if argv is None else argv 554 | 555 | usage_sections = parse_section('usage:', doc) 556 | if len(usage_sections) == 0: 557 | raise DocoptLanguageError('"usage:" (case-insensitive) not found.') 558 | if len(usage_sections) > 1: 559 | raise DocoptLanguageError('More than one "usage:" (case-insensitive).') 560 | DocoptExit.usage = usage_sections[0] 561 | 562 | options = parse_defaults(doc) 563 | pattern = parse_pattern(formal_usage(DocoptExit.usage), options) 564 | # [default] syntax for argument is disabled 565 | #for a in pattern.flat(Argument): 566 | # same_name = [d for d in arguments if d.name == a.name] 567 | # if same_name: 568 | # a.value = same_name[0].value 569 | argv = parse_argv(Tokens(argv), list(options), options_first) 570 | pattern_options = set(pattern.flat(Option)) 571 | for options_shortcut in pattern.flat(OptionsShortcut): 572 | doc_options = parse_defaults(doc) 573 | options_shortcut.children = list(set(doc_options) - pattern_options) 574 | #if any_options: 575 | # options_shortcut.children += [Option(o.short, o.long, o.argcount) 576 | # for o in argv if type(o) is Option] 577 | extras(help, version, argv, doc) 578 | matched, left, collected = pattern.fix().match(argv) 579 | if matched and left == []: # better error message if left? 580 | return Dict((a.name, a.value) for a in (pattern.flat() + collected)) 581 | raise DocoptExit() 582 | 583 | -------------------------------------------------------------------------------- /senna.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -*- coding: utf-8 -*- 2 | 3 | """NLTK Command Line Interface - Senna API 4 | 5 | Usage: 6 | senna.py (-h | --help) 7 | senna.py --version 8 | senna.py --sennadir PATH --postag --input FILE [--output NONE] 9 | senna.py --sennadir PATH --nertag --input FILE [--output NONE] 10 | senna.py --sennadir PATH --chunktag --input FILE [--output NONE] 11 | senna.py --sennadir PATH --np FILE 12 | senna.py --sennadir PATH --chunk CHUNKTYPE FILE 13 | senna.py --np FILE [--output NONE] 14 | senna.py --vp FILE [--output NONE] 15 | senna.py --chunk CHUNKTYPE FILE [--output NONE] 16 | senna.py --postag FILE [--output NONE] 17 | senna.py --nertag FILE [--output NONE] 18 | senna.py --chunktag FILE [--output NONE] 19 | senna.py --chunk2 CHUNKTYPES FILE 20 | 21 | Options: 22 | -h --help Show this screen. 23 | --sennadir Path to jar file (Complusory) 24 | --input Path to input file. 25 | --output Path to output file [default: None]. 26 | --postag Option to POS tag a file. 27 | --nertag Option to NER tag a file. 28 | --chunktag Option to chunk (i.e. BIO tag) a file. 29 | --chunk CHUNKTYPE TL;DR, "I just want to extract CHUNKTYPE from this file". 30 | --np TL;DR, "I just want to extract NPs from this file". 31 | --vp TL;DR, "I just want to extract VPs from this file". 32 | --chunk2 CHUNKTYPE TL;DR, "I just want to combine CHUNKTYPES (e.g. VP+ADJP) from this file". 33 | """ 34 | 35 | from __future__ import print_function 36 | import io 37 | import os 38 | import re 39 | 40 | from nltk import word_tokenize 41 | from nltk.tag.senna import SennaTagger, SennaNERTagger, SennaChunkTagger 42 | 43 | from docopt import docopt 44 | 45 | senna_tool = { 46 | '--postag': SennaTagger, 47 | '--nertag': SennaNERTagger, 48 | '--chunktag': SennaChunkTagger, 49 | '--chunk': SennaChunkTagger, 50 | '--chunk2': SennaChunkTagger, 51 | } 52 | 53 | 54 | def initialize_tool(arguments): 55 | process = next(k for k,v in arguments.items() if k in senna_tool and v) 56 | tool = senna_tool[process](arguments['--sennadir']) 57 | return tool, process 58 | 59 | def augment_arguments(arguments): 60 | if arguments['--sennadir'] is None: 61 | homedir = os.path.expanduser("~") 62 | arguments['--sennadir'] = homedir + '/senna/' 63 | if '--np' in arguments and arguments['--np']: 64 | arguments['--chunk'] = 'NP' 65 | if '--vp' in arguments and arguments['--vp']: 66 | arguments['--chunk'] = 'VP' 67 | 68 | 69 | def initialize_iofiles(arugments): 70 | infile, outfile = "", "" 71 | if arguments['FILE']: 72 | infile = arguments['FILE'] 73 | elif arguments['--input']: 74 | infile = arguments['--input'] 75 | if arugments['--output']: 76 | outfile = arugments['--output'] 77 | return infile, outfile 78 | 79 | 80 | def senna_tag_sents(sentences, tool, chunk_type=None): 81 | tagged_sents = tool.tag_sents(sentences) 82 | for sent in tagged_sents: 83 | yield " ".join(word + '#' + pos for word, pos in sent) 84 | 85 | def senna_extract_chunks(sentences, chunker, chunk_type): 86 | tagged_sents = chunker.tag_sents(sentences) 87 | for tagged_sent in tagged_sents: 88 | chunk_outputs = list(chunker.bio_to_chunks(tagged_sent, chunk_type)) 89 | if chunk_outputs: 90 | chunks, positions = zip(*chunk_outputs) 91 | yield "|".join(chunks) 92 | else: 93 | yield str("!!! NO CHUNK of " + chunk_type + " in this sentence !!!") 94 | 95 | def senna_extract_combined_chunks(sentences, chunker, chunk_types): 96 | _chunk_types = chunk_types.split('+') 97 | tagged_sents = chunker.tag_sents(sentences) 98 | 99 | for tagged_sent in tagged_sents: 100 | chunks1 = list(chunker.bio_to_chunks(tagged_sent, _chunk_types[0])) 101 | chunks2 = list(chunker.bio_to_chunks(tagged_sent, _chunk_types[1])) 102 | 103 | chunk_combinations = [] 104 | jumper = 0 105 | for chunk1 in chunks1: 106 | chunk1_end_position = int(chunk1[1].split('-')[-1]) 107 | for i, chunk2 in enumerate(chunks2[jumper:]): 108 | chunk2_start_position = int(chunk2[1].split('-')[0]) 109 | if chunk2_start_position == chunk1_end_position+1: 110 | jumper = i 111 | chunks, positions = zip(*[chunk1, chunk2]) 112 | chunk_combinations.append("\t".join(chunks)) 113 | if chunk_combinations: 114 | yield ('|'.join(chunk_combinations)) 115 | else: 116 | yield str("!!! NO CHUNK of " + chunk_types + " in this sentence !!!") 117 | 118 | 119 | 120 | if __name__ == '__main__': 121 | arguments = docopt(__doc__, version='NLTK CLI (Senna Tools) version 0.0.1') 122 | # Augment arguments for TL;DR commands. 123 | augment_arguments(arguments) 124 | # Initialize tool. 125 | tool, process = initialize_tool(arguments) 126 | infile, outfile = initialize_iofiles(arguments) 127 | # Initialize output file. 128 | if outfile: 129 | fout = io.open(outfile, 'w', encoding='utf8') 130 | 131 | if arguments['--chunk']: 132 | process = senna_extract_chunks 133 | elif arguments['--chunk2']: 134 | process = senna_extract_combined_chunks 135 | arguments['--chunk'] = arguments['--chunk2'] 136 | else: 137 | process = senna_tag_sents 138 | 139 | with io.open(infile, 'r', encoding='utf8') as fin: 140 | sentences = [word_tokenize(line.strip()) for line in fin] 141 | for processed_sent in process(sentences, tool, arguments['--chunk']): 142 | if outfile: 143 | fout.write(processed_sent + '\n') 144 | else: 145 | print(processed_sent) 146 | 147 | -------------------------------------------------------------------------------- /stanford.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -*- coding: utf-8 -*- 2 | 3 | """NLTK Command Line Interface - Stanford API 4 | 5 | Usage: 6 | stanford.py --tool=postagger --jar FILE --model PATH --input FILE [--output NONE] 7 | stanford.py --tool=neragger --jar FILE --model PATH --input FILE [--output NONE] 8 | stanford.py --tool=lexparser --jar FILE --modeljar FILE --model PATH --input FILE [--output NONE] 9 | stanford.py (-h | --help) 10 | stanford.py --version 11 | 12 | stanford.py --postag FILE [--lang LANG] [--output NONE] 13 | stanford.py --lexparse FILE [--lang LANG] [--output NONE] 14 | stanford.py --nertag FILE [--lang LANG] [--output NONE] 15 | 16 | stanford.py --postag FILE [--model PATH] [--output NONE] 17 | stanford.py --lexparse FILE [--model PATH] [--output NONE] 18 | stanford.py --nertag FILE [--model LANG] [--output NONE] 19 | 20 | Options: 21 | -h --help Show this screen. 22 | --tool Tagger/Parser option (i.e. 'lexparser', 'postagger', etc.) 23 | --jar Path to jar file (Complusory) 24 | --model Path to model name (Complusory). 25 | --modeljar Path to model jar file (Only use with Stanford parsers). 26 | --input Path to input file. 27 | --output Path to output file [default: None]. 28 | --postag TL;DR, "I just want to POS tag this file" [default: eng]. 29 | --nertag TL;DR, "I just want to NER tag this file" (only English). 30 | --lexparse TL;DR, "I just want to parse this file" [default: eng]. 31 | --lang The language option for TL;DR options [default: eng]. 32 | """ 33 | 34 | from __future__ import print_function 35 | import io 36 | import os 37 | import re 38 | 39 | 40 | from nltk.tag.stanford import StanfordPOSTagger, StanfordNERTagger 41 | from nltk.parse.stanford import StanfordParser 42 | #from nltk.parse.stanford import StanfordDependencyParser 43 | #from nltk.parse.stanford import StanfordNeuralDependencyParser 44 | 45 | from docopt import docopt 46 | 47 | 48 | taggers = { 49 | 'postagger': StanfordPOSTagger, 50 | 'nertagger':StanfordNERTagger 51 | } 52 | 53 | 54 | parsers = { 55 | 'lexparser':StanfordParser, 56 | #'depparser':StanfordDependencyParser, # Not coded yet. 57 | #'neuralparser':StanfordNeuralDependencyParser # Not coded yet. 58 | } 59 | 60 | 61 | lexparser_languages = { 62 | # Arabic 63 | 'ara': ['arabicFactored.ser.gz'], 64 | # Chinese 65 | 'cmn': ['chinesePCFG.ser.gz', 'chineseFactored.ser.gz', 66 | 'xinhuaPCFG.ser.gz', 'xinhuaFactored.ser.gz', 'xinhuaFactoredSegmenting.ser.gz'], 67 | # German 68 | 'deu':['germanPCFG.ser.gz', 'germanFactored.ser.gz'], 69 | # English 70 | 'eng': ['englishRNN.ser.gz', 'englishPCFG.ser.gz', 71 | 'englishFactored.ser.gz', 'englishPCFG.caseless.ser.gz', 'wsjPCFG.ser.gz', 72 | 'wsjRNN.ser.gz', 'wsjFactored.ser.gz'], 73 | # French 74 | 'fre': ['frenchFactored.ser.gz'], 75 | # Spanish 76 | 'spa': ['spanishPCFG.ser.gz']} 77 | 78 | postagger_languages = { 79 | # Arabic 80 | 'ara': ['arabic.tagger'], 81 | # Chinese 82 | 'cmn': ['chinese-distsim.tagger', 'chinese-nodistsim.tagger'], 83 | # English 84 | 'eng': ['english-bidirectional-distsim.tagger', 85 | 'english-caseless-left3words-distsim.tagger', 86 | 'english-left3words-distsim.tagger', 'wsj-0-18-bidirectional-distsim.tagger', 87 | 'wsj-0-18-bidirectional-nodistsim.tagger', 88 | 'wsj-0-18-caseless-left3words-distsim.tagger', 89 | 'wsj-0-18-left3words-distsim.tagger', 'wsj-0-18-left3words-nodistsim.tagger'], 90 | # French 91 | 'fre': ['french.tagger'], 92 | # German 93 | 'deu': ['german-dewac.tagger', 'german-fast-caseless.tagger', 94 | 'german-fast.tagger', 'german-hgc.tagger'], 95 | # Spanish 96 | 'spa': ['spanish-distsim.tagger', 'spanish.tagger'] 97 | } 98 | 99 | nertagger_languages = { 100 | # Chinese 101 | 'cmn': ['chinese.misc.distsim.crf.ser.gz'], 102 | # German 103 | 'deu': ['german.dewac_175m_600.crf.ser.gz', 'german.hgc_175m_600.crf.ser.gz'], 104 | # English 105 | 'eng': ['english.all.3class.distsim.crf.ser.gz', 'english.conll.4class.distsim.crf.ser.gz', 106 | 'english.muc.7class.distsim.crf.ser.gz', 'example.serialized.ncc.ncc.ser.gz'], 107 | # Spansih 108 | 'spa': ['spanish.ancora.distsim.s512.crf.ser.gz'] 109 | } 110 | 111 | def stanford_tag_sents(sentences, tagger): 112 | tagged_sents = tagger.tag_sents(sentences) 113 | for sent in tagged_sents: 114 | yield " ".join(word + '#' + pos for word, pos in sent) 115 | 116 | def stanford_parse_sents(sentences, parser): 117 | parsed_sents = sum([list(i) for i in parser.parse_sents(sentences)], []) 118 | return [re.sub(' +',' ', str(sent).replace('\n', '')) for sent in parsed_sents] 119 | 120 | def initialize_tool(arguments): 121 | """ 122 | To initalize the Stanford tools given the users arguments from command line. 123 | """ 124 | tool_name = arguments['--tool'] 125 | if tool_name in taggers: 126 | tagger = taggers[tool_name](model_filename=arguments['--model'], path_to_jar=arguments['--jar']) 127 | return tagger, stanford_tag_sents 128 | elif tool_name in parsers: 129 | parser = parsers[tool_name](model_path=arguments['--model'], path_to_models_jar=arguments['--modeljar'], path_to_jar=arguments['--jar']) 130 | return parser, stanford_parse_sents 131 | 132 | 133 | def initialize_iofiles(arugments): 134 | infile, outfile = "", "" 135 | if arguments['FILE']: 136 | infile = arguments['FILE'] 137 | elif arguments['--input']: 138 | infile = arguments['--input'] 139 | if arugments['--output']: 140 | outfile = arugments['--output'] 141 | return infile, outfile 142 | 143 | def augment_arugments(arguments): 144 | homedir = os.path.expanduser("~") 145 | # Augment arugments for LexParser. 146 | if '--lexparse' in arguments.keys() and arguments['--lexparse']: 147 | arguments['--tool'] = 'lexparser' 148 | arguments['--jar'] = homedir +'/stanford-parser/stanford-parser.jar' 149 | arguments['--modeljar'] = homedir +'/stanford-parser/stanford-parser-3.5.2-models.jar' 150 | if arguments['--model'] is None: 151 | if arguments['--lang'] == None: 152 | arguments['--model'] = 'edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz' 153 | else: 154 | arguments['--model'] = 'edu/stanford/nlp/models/lexparser/' 155 | arguments['--model']+= lexparser_languages[arguments['--lang']][0] 156 | # Augment arugments for POSTagger. 157 | elif '--postag' in arguments.keys() and arguments['--postag']: 158 | arguments['--tool'] = 'postagger' 159 | arguments['--jar'] = homedir +'/stanford-postagger/stanford-postagger.jar' 160 | if arguments['--model'] is None: 161 | if arguments['--lang'] == None: 162 | arguments['--model'] = homedir + '/stanford-postagger/models/english-bidirectional-distsim.tagger' 163 | else: 164 | arguments['--model'] = homedir + '/stanford-postagger/models/' 165 | arguments['--model']+= postagger_languages[arguments['--lang']][0] 166 | # Augment arugments for NERTagger. 167 | elif '--nertag' in arguments.keys() and arguments['--nertag']: 168 | arguments['--tool'] = 'nertagger' 169 | arguments['--jar'] = homedir +'/stanford-ner/stanford-ner.jar' 170 | if arguments['--model'] is None: 171 | if arguments['--lang'] == None: 172 | arguments['--model'] = homedir + '/stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz' 173 | else: 174 | arguments['--model'] = homedir + '/stanford-ner/classifiers/' 175 | arguments['--model']+= nertagger_languages[arguments['--lang']][0] 176 | 177 | 178 | if __name__ == '__main__': 179 | arguments = docopt(__doc__, version='NLTK CLI (Stanford Tools) version 0.0.1') 180 | # Augment arguments for TL;DR commands. 181 | if arguments['--tool'] is None: 182 | augment_arugments(arguments) 183 | 184 | tool, process = initialize_tool(arguments) 185 | infile, outfile = initialize_iofiles(arguments) 186 | if outfile: 187 | fout = io.open(outfile, 'w', encoding='utf8') 188 | with io.open(infile, 'r', encoding='utf8') as fin: 189 | sentences = [line.strip().split() for line in fin] 190 | for processed_sent in process(sentences, tool): 191 | if outfile: 192 | fout.write(processed_sent + '\n') 193 | else: 194 | print(processed_sent) 195 | 196 | 197 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | Fish Head Curry 2 | Originally created by Singapore’s Malayalee (an Indian ethnic group from the Southern Indian state of Kerala) community, it is prepared by stewing the head of an ikan merah (red snapper fish) in a spicy-hot curry with vegetables; with the sour-tasting tamarind flavour an unmistakable signature of this dish. 3 | Visitors can either have it with rice or as the Chinese do it - wipe the curry gravy clean with a soft bun. 4 | The sweetness of the dough helps to neutralize the spices in the curry - a great way to enjoy the dish even if you have a low tolerance for spice. 5 | The Chinese tend to have it alongside smaller dishes of vegetables and meat; head down to McCullum Street in the heart of the city for a taste at the famous Ocean Fish Head Curry eatery. 6 | The Indians likewise tend to eat it in a similar manner, having it with rice, pappadams and Indian pickle; check out the Banana Leaf Apolo in Little India, as well as the famous Muthu’s Curry on Race Course Road, which is just a few yards away. 7 | Savour the soft chunks of meat and dig into the eyes of the fish and complement the spicy flavours with a tall glass of Kingfisher (Indian beer) or ice-cold lemonade. 8 | This is another dish you must have during your visit here, as you are unlikely to find something like this anywhere else in the world. 9 | --------------------------------------------------------------------------------