├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.rst ├── documentation ├── Makefile ├── img │ └── output.png ├── requirements.txt └── source │ ├── _static │ ├── gif │ │ └── commandline.gif │ └── img │ │ ├── list_of_grievances.png │ │ └── output.png │ ├── api │ ├── rnlp.corpus.rst │ ├── rnlp.parse.rst │ ├── rnlp.rst │ └── rnlp.textprocessing.rst │ ├── conf.py │ ├── getting_started │ ├── 01_environment.rst │ ├── 02_installation.rst │ ├── 03_quickstart.rst │ └── 04_learning.rst │ └── index.rst ├── example_files ├── d.txt ├── d1.txt ├── d2.txt ├── d3.txt ├── d4.txt ├── d5.txt ├── d6.txt └── doi.txt ├── requirements.txt ├── rnlp ├── __init__.py ├── __main__.py ├── _meta.py ├── check_state.py ├── corpus.py ├── parse.py ├── tests │ ├── __init__.py │ ├── requirements.txt │ ├── rnlptests │ │ ├── __init__.py │ │ ├── test_converter.py │ │ ├── test_parse.py │ │ └── test_textprocessing.py │ └── tests.py └── textprocessing.py ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | train 3 | test 4 | files2 5 | 6 | bk.txt 7 | blockIDs.txt 8 | facts.txt 9 | sentenceIDs.txt 10 | wordIDs.txt 11 | 12 | .DS_Store 13 | # === The following are based on the github/gitignore/Python.gitignore === # 14 | # === Made available under a Creative Commons Zero v1.0 Universal ======== # 15 | 16 | # Byte-compiled / optimized / DLL files 17 | __pycache__/ 18 | *.py[cod] 19 | *$py.class 20 | 21 | # C extensions 22 | *.so 23 | 24 | # Distribution / packaging 25 | .Python 26 | build/ 27 | develop-eggs/ 28 | dist/ 29 | downloads/ 30 | eggs/ 31 | .eggs/ 32 | lib/ 33 | lib64/ 34 | parts/ 35 | sdist/ 36 | var/ 37 | wheels/ 38 | *.egg-info/ 39 | .installed.cfg 40 | *.egg 41 | MANIFEST 42 | 43 | # PyInstaller 44 | # Usually these files are written by a python script from a template 45 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 46 | *.manifest 47 | *.spec 48 | 49 | # Installer logs 50 | pip-log.txt 51 | pip-delete-this-directory.txt 52 | 53 | # Unit test / coverage reports 54 | htmlcov/ 55 | .tox/ 56 | .coverage 57 | .coverage.* 58 | .cache 59 | nosetests.xml 60 | coverage.xml 61 | *.cover 62 | .hypothesis/ 63 | .pytest_cache/ 64 | 65 | # Translations 66 | *.mo 67 | *.pot 68 | 69 | # Django stuff: 70 | *.log 71 | local_settings.py 72 | db.sqlite3 73 | 74 | # Flask stuff: 75 | instance/ 76 | .webassets-cache 77 | 78 | # Scrapy stuff: 79 | .scrapy 80 | 81 | # Sphinx documentation 82 | docs/_build/ 83 | 84 | # PyBuilder 85 | target/ 86 | 87 | # Jupyter Notebook 88 | .ipynb_checkpoints 89 | 90 | # pyenv 91 | .python-version 92 | 93 | # celery beat schedule file 94 | celerybeat-schedule 95 | 96 | # SageMath parsed files 97 | *.sage.py 98 | 99 | # Environments 100 | .env 101 | .venv 102 | env/ 103 | venv/ 104 | ENV/ 105 | env.bak/ 106 | venv.bak/ 107 | 108 | # Spyder project settings 109 | .spyderproject 110 | .spyproject 111 | 112 | # Rope project settings 113 | .ropeproject 114 | 115 | # mkdocs documentation 116 | /site 117 | 118 | #pycharm stuff 119 | .idea/ 120 | 121 | # mypy 122 | .mypy_cache/ 123 | 124 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: python 4 | 5 | env: 6 | - SH=bash 7 | 8 | python: 9 | - "3.4" 10 | - "3.5" 11 | - "3.6" 12 | - "3.6-dev" 13 | - "3.7-dev" 14 | 15 | cache: 16 | pip: true 17 | directories: 18 | - $HOME/nltk_data 19 | 20 | install: 21 | - "pip install -r rnlp/tests/requirements.txt" 22 | - "python -m nltk.downloader stopwords punkt averaged_perceptron_tagger -d $HOME/nltk_data" 23 | 24 | script: 25 | - coverage run rnlp/tests/tests.py 26 | 27 | before_install: 28 | export NLTK_DATA="$HOME/nltk_data"; 29 | pip install codecov 30 | 31 | after_success: 32 | codecov 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Alexander L. Hayes 2 | 3 | .PHONY : distribution 4 | 5 | distribution: 6 | pip install --upgrade setuptools wheel twine 7 | rm -rf dist/ rnlp.egg-info/ build/ 8 | python setup.py sdist bdist_wheel 9 | python -m twine upload dist/* 10 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ######## 2 | ``rnlp`` 3 | ######## 4 | 5 | |PyPi|_ |License|_ |Travis|_ |Codecov|_ |ReadTheDocs|_ 6 | 7 | .. |PyPi| image:: https://img.shields.io/pypi/v/rnlp.svg 8 | :alt: Python Package Index (PyPi) latest version. 9 | .. _PyPi: https://pypi.org/project/rnlp/ 10 | 11 | .. |License| image:: https://img.shields.io/github/license/hayesall/rnlp.svg 12 | :alt: License. 13 | .. _License: https://github.com/hayesall/rnlp/blob/master/LICENSE 14 | 15 | .. |Travis| image:: https://travis-ci.org/hayesall/rnlp.svg?branch=master 16 | :alt: Master branch build status. 17 | .. _Travis: https://travis-ci.org/hayesall/rnlp 18 | 19 | .. |Codecov| image:: https://codecov.io/gh/hayesall/rnlp/branch/master/graphs/badge.svg?branch=master 20 | :alt: Master branch code coverage. 21 | .. _Codecov: https://codecov.io/github/hayesall/rnlp?branch=master 22 | 23 | .. |ReadTheDocs| image:: https://readthedocs.org/projects/rnlp/badge/?version=latest 24 | :alt: Documentation build status and link to documentation. 25 | .. _ReadTheDocs: http://rnlp.readthedocs.io/en/latest/ 26 | 27 | Relational NLP Preprocessing (**rnlp**): A Python package and tool for converting text into a set of relational facts. 28 | 29 | - **Documentation**: https://rnlp.readthedocs.io/en/latest/ 30 | - **Questions?**: Contact `Alexander L. Hayes (hayesall) `_ 31 | 32 | Installation 33 | ------------ 34 | 35 | Stable builds on PyPi 36 | 37 | .. code-block:: bash 38 | 39 | pip install rnlp 40 | 41 | Quick-Start 42 | ----------- 43 | 44 | ``rnlp`` can be used either as a command line interface (CLI) tool or as an imported Python Package. 45 | 46 | +---------------------------------------------+--------------------------------------+ 47 | | **CLI** | **Imported** | 48 | +---------------------------------------------+--------------------------------------+ 49 | |.. code-block:: bash |.. code-block:: python | 50 | | | | 51 | | $ python -m rnlp -f example_files/doi.txt | from rnlp.corpus import declaration | 52 | | Reading corpus from file(s)... | import rnlp | 53 | | Creating background file... | | 54 | | 100%|████████| 18/18 [00:00<00:00, 38it/s] | doi = declaration() | 55 | | | rnlp.converter(doi) | 56 | +---------------------------------------------+--------------------------------------+ 57 | 58 | The relations created by ``rnlp`` include the following: 59 | 60 | * Sentence's Relative Position in Block: 61 | 62 | * ``earlySentenceInBlock``: Sentence occurs within the first third of a block. 63 | * ``midWaySentenceInBlock``: Sentence occurs between the first third and the last third of a block's length. 64 | * ``lateSentenceInBlock``: Sentence occurs within the last third of a block's length. 65 | 66 | * Word's Relative Position in Sentence: 67 | 68 | * ``earlyWordInSentence``: Word occurs within the first third of a sentence. 69 | * ``midWayWordInSentence``: Word occurs between a third and two-thirds of a sentence. 70 | * ``lateWordInSentence``: Word occurs within the last third of a sentence. 71 | 72 | * Relative Position Between Items: 73 | 74 | * ``nextWordInSentence``: Pointer from a word to its neighbor. 75 | * ``nextSentenceInBlock``: Pointer from a sentence to its neighbor. 76 | 77 | * Existential Semantics: 78 | 79 | * ``sentenceInBlock``: Sentence occurs in a particular block. 80 | * ``wordInSentence``: Word occurs in a particular sentence. 81 | 82 | * Low-Level Information about words: 83 | 84 | * ``wordString``: A string representation of a word. 85 | * ``partOfSpeechTag``: The word's part of speech (as determined by the nltk part-of-speech tagger). 86 | 87 | --- 88 | 89 | Files contain a toy corpus (``example files/``) and an image of a BoostSRL tree for predicting if a word in a sentence is the word "you". 90 | 91 | .. image:: https://raw.githubusercontent.com/hayesall/rnlp/master/documentation/img/output.png 92 | 93 | The tree says that if the word string contained in word 'b' is "you" then 'b' is the word "you" with a high probability. (This is of course true). 94 | A more interesting inference is the False branch that says that if word 'b' is an early word in sentence 'a' and word 'anon12035' is also an early word in sentence 'a' and if the word string contained in word 'anon12035' is "Thank", then the word 'b' has decent chance of being the word "you". (The model was able to learn that the word "you" often occurs with the word "Thank" in the same sentence when "Thank" appears early in that sentence). 95 | -------------------------------------------------------------------------------- /documentation/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = rnlp 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /documentation/img/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/documentation/img/output.png -------------------------------------------------------------------------------- /documentation/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx_rtd_theme 2 | sphinx 3 | -------------------------------------------------------------------------------- /documentation/source/_static/gif/commandline.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/documentation/source/_static/gif/commandline.gif -------------------------------------------------------------------------------- /documentation/source/_static/img/list_of_grievances.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/documentation/source/_static/img/list_of_grievances.png -------------------------------------------------------------------------------- /documentation/source/_static/img/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/documentation/source/_static/img/output.png -------------------------------------------------------------------------------- /documentation/source/api/rnlp.corpus.rst: -------------------------------------------------------------------------------- 1 | ====================== 2 | ``rnlp.corpus`` module 3 | ====================== 4 | 5 | .. automodule:: rnlp.corpus 6 | :members: 7 | :undoc-members: 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /documentation/source/api/rnlp.parse.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | ``rnlp.parse`` module 3 | ===================== 4 | 5 | .. automodule:: rnlp.parse 6 | :members: 7 | :undoc-members: 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /documentation/source/api/rnlp.rst: -------------------------------------------------------------------------------- 1 | ========================== 2 | ``rnlp``: Package Overview 3 | ========================== 4 | 5 | .. automodule:: rnlp 6 | :members: 7 | :undoc-members: 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /documentation/source/api/rnlp.textprocessing.rst: -------------------------------------------------------------------------------- 1 | ============================== 2 | ``rnlp.textprocessing`` module 3 | ============================== 4 | 5 | .. automodule:: rnlp.textprocessing 6 | :members: 7 | :undoc-members: 8 | :show-inheritance: 9 | -------------------------------------------------------------------------------- /documentation/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # rnlp documentation build configuration file, created by 5 | # sphinx-quickstart on Thu May 17 10:12:50 2018. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('../..')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = ['sphinx.ext.autodoc', 35 | 'sphinx.ext.viewcode', 36 | 'sphinx.ext.githubpages'] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix(es) of source filenames. 42 | # You can specify multiple suffix as a list of string: 43 | # 44 | # source_suffix = ['.rst', '.md'] 45 | source_suffix = '.rst' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = 'rnlp' 52 | copyright = '2019 Alexander L. Hayes' 53 | author = 'Alexander L. Hayes (@hayesall)' 54 | 55 | # The version info for the project you're documenting, acts as replacement for 56 | # |version| and |release|, also used in various other places throughout the 57 | # built documents. 58 | # 59 | # The short X.Y version. 60 | version = '0.3.0' 61 | # The full version, including alpha/beta/rc tags. 62 | release = '0.3.0' 63 | 64 | # The language for content autogenerated by Sphinx. Refer to documentation 65 | # for a list of supported languages. 66 | # 67 | # This is also used if you do content translation via gettext catalogs. 68 | # Usually you set "language" from the command line for these cases. 69 | language = None 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | # This patterns also effect to html_static_path and html_extra_path 74 | exclude_patterns = [] 75 | 76 | # The name of the Pygments (syntax highlighting) style to use. 77 | pygments_style = 'sphinx' 78 | 79 | # If true, `todo` and `todoList` produce output, else they produce nothing. 80 | todo_include_todos = False 81 | 82 | 83 | # -- Options for HTML output ---------------------------------------------- 84 | 85 | # The theme to use for HTML and HTML Help pages. See the documentation for 86 | # a list of builtin themes. 87 | # 88 | html_theme = 'sphinx_rtd_theme' 89 | 90 | # Theme options are theme-specific and customize the look and feel of a theme 91 | # further. For a list of options available for each theme, see the 92 | # documentation. 93 | # 94 | # html_theme_options = {} 95 | 96 | # Add any paths that contain custom static files (such as style sheets) here, 97 | # relative to this directory. They are copied after the builtin static files, 98 | # so a file named "default.css" will overwrite the builtin "default.css". 99 | html_static_path = ['_static'] 100 | 101 | # Custom sidebar templates, must be a dictionary that maps document names 102 | # to template names. 103 | # 104 | # This is required for the alabaster theme 105 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 106 | html_sidebars = { 107 | '**': [ 108 | 'about.html', 109 | 'navigation.html', 110 | 'relations.html', # needs 'show_related': True theme option to display 111 | 'searchbox.html', 112 | 'donate.html', 113 | ] 114 | } 115 | 116 | 117 | # -- Options for HTMLHelp output ------------------------------------------ 118 | 119 | # Output file base name for HTML help builder. 120 | htmlhelp_basename = 'rnlpdoc' 121 | 122 | 123 | # -- Options for LaTeX output --------------------------------------------- 124 | 125 | latex_elements = { 126 | # The paper size ('letterpaper' or 'a4paper'). 127 | # 128 | # 'papersize': 'letterpaper', 129 | 130 | # The font size ('10pt', '11pt' or '12pt'). 131 | # 132 | # 'pointsize': '10pt', 133 | 134 | # Additional stuff for the LaTeX preamble. 135 | # 136 | # 'preamble': '', 137 | 138 | # Latex figure (float) alignment 139 | # 140 | # 'figure_align': 'htbp', 141 | } 142 | 143 | # Grouping the document tree into LaTeX files. List of tuples 144 | # (source start file, target name, title, 145 | # author, documentclass [howto, manual, or own class]). 146 | latex_documents = [ 147 | (master_doc, 'rnlp.tex', 'rnlp Documentation', 148 | 'Alexander L. Hayes (@hayesall)', 'manual'), 149 | ] 150 | 151 | 152 | # -- Options for manual page output --------------------------------------- 153 | 154 | # One entry per manual page. List of tuples 155 | # (source start file, name, description, authors, manual section). 156 | man_pages = [ 157 | (master_doc, 'rnlp', 'rnlp Documentation', 158 | [author], 1) 159 | ] 160 | 161 | 162 | # -- Options for Texinfo output ------------------------------------------- 163 | 164 | # Grouping the document tree into Texinfo files. List of tuples 165 | # (source start file, target name, title, author, 166 | # dir menu entry, description, category) 167 | texinfo_documents = [ 168 | (master_doc, 'rnlp', 'rnlp Documentation', 169 | author, 'rnlp', 'One line description of project.', 170 | 'Miscellaneous'), 171 | ] 172 | -------------------------------------------------------------------------------- /documentation/source/getting_started/01_environment.rst: -------------------------------------------------------------------------------- 1 | ================= 2 | Environment Setup 3 | ================= 4 | 5 | The first step is to get Python running on your machine (skip to the next step if you've already done this). 6 | 7 | Linux (yum/dnf) 8 | --------------- 9 | 10 | .. code-block:: bash 11 | 12 | $ sudo yum update 13 | $ sudo yum install python 14 | 15 | Linux (apt-get) 16 | --------------- 17 | 18 | .. code-block:: bash 19 | 20 | $ sudo apt-get update 21 | $ sudo apt-get upgrade 22 | $ sudo apt-get install python 23 | 24 | Windows 25 | ------- 26 | 27 | Download Python from `python.org `_ or `anaconda.com `_. 28 | 29 | A fairly in-depth guide is available as part of the `Conda documentation `_. 30 | -------------------------------------------------------------------------------- /documentation/source/getting_started/02_installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | Stable builds on PyPi 6 | 7 | .. code-block:: bash 8 | 9 | pip install rnlp 10 | 11 | Some modules in nltk need to be available: 12 | 13 | .. code-block:: bash 14 | 15 | import nltk 16 | nltk.download('punkt') 17 | nltk.download('stopwords') 18 | nltk.download('averaged_perceptron_tagger') 19 | -------------------------------------------------------------------------------- /documentation/source/getting_started/03_quickstart.rst: -------------------------------------------------------------------------------- 1 | =========== 2 | Quick Start 3 | =========== 4 | 5 | Relations 6 | --------- 7 | 8 | The relations created by ``rnlp`` include the following: 9 | 10 | * Sentence’s Relative Position in Block: 11 | 12 | * ``earlySentenceInBlock``: Sentence occurs within the first third of a block’s length. 13 | * ``midWaySentenceInBlock``: Sentence occurs between the first and last third of a block’s length. 14 | * ``lateSentenceInBlock``: Sentence occurs within the last third of a block’s length. 15 | 16 | * Word’s Relative Position in Sentence: 17 | 18 | * ``earlyWordInSentence``: Word occurs within the first third of a sentence. 19 | * ``midWayWordInSentence``: Word occurs between a third and two-thirds of a sentence. 20 | * ``lateWordInSentence``: Word occurs within the last third of a sentence. 21 | 22 | * Relative Position Between Items: 23 | 24 | * ``nextWordInSentence``: Pointer from a word to its neighbor. 25 | * ``nextSentenceInBlock``: Pointer from a sentence to its neighbor. 26 | 27 | * Existential Semantics: 28 | 29 | * ``sentenceInBlock``: Sentence occurs in a particular block. 30 | * ``wordInSentence``: Word occurs in a particular sentence. 31 | 32 | * Low-Level Information about words: 33 | 34 | * ``wordString``: A string representation of a word. 35 | * ``partOfSpeechTag``: The word's part of speech (as determined by the nltk part-of-speech tagger). 36 | 37 | From text to Relational Facts 38 | ----------------------------- 39 | 40 | Consider the example file ``example_files/doi.txt``, the U.S. Declaration of Independence: 41 | 42 | .. code-block:: text 43 | 44 | In Congress, July 4, 1776. The unanimous Declaration of the thirteen united 45 | States of America, When in the Course of human events, it becomes necessary 46 | for one people to dissolve the political bands which have connected them 47 | with another, and to assume among the powers of the earth, the separate and 48 | equal station to which the Laws of Nature and of Nature's God entitle them, 49 | a decent respect to the opinions of mankind requires that they should 50 | declare the causes which impel them to the separation. 51 | ... 52 | ... 53 | 54 | ``rnlp`` can be used either as a commandline tool or as an imported Python Package. 55 | 56 | **Commandline** 57 | 58 | .. code-block:: bash 59 | 60 | $ python -m rnlp -f example_files/doi.txt 61 | Reading corpus from file(s)... 62 | Creating background file... 63 | 100%|████████| 18/18 [00:00<00:00, 38it/s] 64 | 65 | **Imported** 66 | 67 | .. code-block:: python 68 | 69 | from rnlp.corpus import declaration 70 | import rnlp 71 | 72 | doi = declaration() 73 | rnlp.converter(doi) 74 | 75 | 76 | .. code-block:: prolog 77 | 78 | nextSentenceInBlock(1,1_1,1_2). 79 | earlySentenceInBlock(1,1_1). 80 | sentenceInBlock(1_1,1). 81 | wordString(1_1_1,'In'). 82 | partOfSpeech(1_1_1,"IN"). 83 | nextWordInSentence(1_1,1_1_1,1_1_2). 84 | earlyWordInSentence(1_1,1_1_1). 85 | wordInSentence(1_1_1,1_1). 86 | wordString(1_1_2,'Congress'). 87 | partOfSpeech(1_1_2,"NNP"). 88 | ... 89 | ... 90 | -------------------------------------------------------------------------------- /documentation/source/getting_started/04_learning.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Learning 3 | ======== 4 | 5 | *This is a brief overview of a learning task. Requirements for a more specific task may vary substantially based on the goals or the data available to you.* 6 | 7 | We now have ``bk.txt`` and ``facts.txt`` as a result of the previous step. In order to get show some results, we will construct a toy data set from predicates easily available in the facts file. 8 | 9 | The *Declaration of Independence* contains a set of phrases called the "List of Grievances", where the Founders spell out the 27 violations by King George III. 10 | 11 | We can turn these into a text classification task where we learn the structure of the grievances. 12 | 13 | Positive and Negative Examples 14 | ------------------------------ 15 | 16 | Labeling data is often a task of its own, but we will take a shortcut and label sentences beginning with **"He"** or **"For"** as being positive examples. Everything else is labeled as negative. 17 | 18 | 1. Create a 'train' directory for our training data. 19 | 20 | .. code-block:: bash 21 | 22 | mkdir train 23 | 24 | 2. This combination of grep, awk, and sort finds all occurances of "He" and "For" in the facts; labels them as a positive example; and adds them to a train_pos.txt file. 25 | 26 | .. code-block:: bash 27 | 28 | grep "'He'\|'For'" facts.txt | 29 | awk '{gsub("wordString","sentenceContainsTarget"); 30 | gsub("_[0-9]*,.*",")."); 31 | print}' | 32 | sort -u > train/train_pos.txt 33 | 34 | 3. This command does something similar, but returns all sentences *not* containing the example. 35 | 36 | .. code-block:: bash 37 | 38 | grep "wordString" facts.txt | 39 | grep -v "'He'\|'For'" | 40 | awk '{gsub("wordString","sentenceContainsTarget"); 41 | gsub("_[0-9]*,.*",")."); 42 | print}' | 43 | sort -u > train/train_neg.txt 44 | 45 | 4. Some sentences have been counted twice--some negative examples are also present in the positive examples. Luckily we can do a set difference to fix this. 46 | 47 | .. code-block:: bash 48 | 49 | sort train/train_neg.txt train/train_pos.txt train/train_pos.txt | 50 | uniq -u > temp; mv temp train/train_neg.txt 51 | 52 | 5. We want to learn about the structure of sentences, so we will replace the default target with our own and move a copy into the train/ directory. 53 | 54 | .. code-block:: bash 55 | 56 | awk '{gsub(".*Target.*", 57 | "mode: sentenceContainsTarget(+SID)."); 58 | print}' bk.txt > train/train_bk.txt 59 | 60 | 6. Finally, move the facts into the same directory. 61 | 62 | .. code-block:: bash 63 | 64 | mv facts.txt train/train_facts.txt 65 | 66 | Our train directory should now contain four files, and the 27 positive examples each correspond to one of the grievances. 67 | 68 | .. code-block:: bash 69 | 70 | train_bk.txt 18 lines 71 | train_facts.txt 6736 lines 72 | train_neg.txt 17 lines 73 | train_pos.txt 27 lines 74 | 75 | BoostSRL 76 | -------- 77 | 78 | Now that our data is organized, we use `BoostSRL `_ for learning. Download a copy of the jar file from the website and move it to the base of the repository. 79 | 80 | .. code-block:: bash 81 | 82 | java -jar v1-0.jar -l -combine \ 83 | -train train/ -target sentenceContainsTarget \ 84 | -trees 25 85 | 86 | .. image:: ../_static/img/list_of_grievances.png 87 | 88 | As expected, the model says that if a word appears early in a sentence, and the string representation of that word is "He": the sentence is likely to be a member of the list of grievances (0.992). 89 | 90 | Otherwise, the model makes the same check for the word "For", assigning a high probability if it is (0.992) and a lower probability if not (0.167). 91 | 92 | We can interpret this model as saying "If an early word in the sentence is 'He' or 'For', the sentence is part of the list of grievances." 93 | -------------------------------------------------------------------------------- /documentation/source/index.rst: -------------------------------------------------------------------------------- 1 | .. rnlp documentation master file, created by 2 | sphinx-quickstart on Thu May 17 10:12:50 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | ``rnlp`` 7 | ======== 8 | 9 | *Relational NLP Preprocessing*: A Python package and tool for converting text 10 | into a set of relational facts. 11 | 12 | 13 | :Source Code: `GitHub `_ 14 | :Bugtracker: `GitHub Issues `_ 15 | 16 | .. image:: https://img.shields.io/pypi/pyversions/rnlp.svg?style=flat-square 17 | .. image:: https://img.shields.io/pypi/v/rnlp.svg?style=flat-square 18 | .. image:: https://img.shields.io/pypi/l/rnlp.svg?style=flat-square 19 | 20 | Overview 21 | -------- 22 | 23 | .. figure:: _static/gif/commandline.gif 24 | 25 | The U.S. Declaration of Independence is available in the corpus submodule for demonstration. Here it is converted to a set of facts using the imported Python package. 26 | 27 | ``rnlp`` is intended to be a general-purpose tool for converting text into relational facts for use with relational reasoning systems (such as `BoostSRL `_). 28 | 29 | Text is converted into relational facts, built around the basic building blocks of *Words*, *Sentences*, and *Blocks*. 30 | 31 | *Words* are individual units of text, such as the words you are currently reading. *Sentences* are a collection of words, often separated by punctuation. *Blocks* are a collection of sentences. 32 | 33 | .. toctree:: 34 | :maxdepth: 1 35 | :caption: Getting Started: 36 | 37 | getting_started/01_environment 38 | getting_started/02_installation 39 | getting_started/03_quickstart 40 | getting_started/04_learning 41 | 42 | .. toctree:: 43 | :maxdepth: 1 44 | :caption: API Reference: 45 | 46 | api/rnlp 47 | api/rnlp.parse 48 | api/rnlp.textprocessing 49 | api/rnlp.corpus 50 | -------------------------------------------------------------------------------- /example_files/d.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d1.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d2.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d3.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d4.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d5.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/d6.txt: -------------------------------------------------------------------------------- 1 | Hello how are you? I am fine thank you.Thank you. 2 | Bye for now. 3 | -------------------------------------------------------------------------------- /example_files/doi.txt: -------------------------------------------------------------------------------- 1 | In Congress, July 4, 1776. The unanimous Declaration of the thirteen united 2 | States of America, When in the Course of human events, it becomes necessary 3 | for one people to dissolve the political bands which have connected them 4 | with another, and to assume among the powers of the earth, the separate and 5 | equal station to which the Laws of Nature and of Nature's God entitle them, 6 | a decent respect to the opinions of mankind requires that they should 7 | declare the causes which impel them to the separation. 8 | 9 | We hold these truths to be self-evident, that all men are created equal, 10 | that they are endowed by their Creator with certain unalienable Rights, 11 | that among these are Life, Liberty and the pursuit of Happiness.--That to 12 | secure these rights, Governments are instituted among Men, deriving their 13 | just powers from the consent of the governed, --That whenever any Form of 14 | Government becomes destructive of these ends, it is the Right of the People 15 | to alter or to abolish it, and to institute new Government, laying its 16 | foundation on such principles and organizing its powers in such form, as 17 | to them shall seem most likely to effect their Safety and Happiness. 18 | Prudence, indeed, will dictate that Governments long established should not 19 | be changed for light and transient causes; and accordingly all experience 20 | hath shewn, that mankind are more disposed to suffer, while evils are 21 | sufferable, than to right themselves by abolishing the forms to which they 22 | are accustomed. But when a long train of abuses and usurpations, pursuing 23 | invariably the same Object evinces a design to reduce them under absolute 24 | Despotism, it is their right, it is their duty, to throw off such 25 | Government, and to provide new Guards for their future security.--Such has 26 | been the patient sufferance of these Colonies; and such is now the 27 | necessity which constrains them to alter their former Systems of 28 | Government. The history of the present King of Great Britain is a history 29 | of repeated injuries and usurpations, all having in direct object the 30 | establishment of an absolute Tyranny over these States. To prove this, let 31 | Facts be submitted to a candid world. 32 | 33 | He has refused his Assent to Laws, the most wholesome and necessary for the 34 | public good. 35 | 36 | He has forbidden his Governors to pass Laws of immediate and pressing 37 | importance, unless suspended in their operation till his Assent should be 38 | obtained; and when so suspended, he has utterly neglected to attend to them. 39 | 40 | He has refused to pass other Laws for the accommodation of large districts 41 | of people, unless those people would relinquish the right of Representation 42 | in the Legislature, a right inestimable to them and formidable to tyrants 43 | only. 44 | 45 | He has called together legislative bodies at places unusual, uncomfortable, 46 | and distant from the depository of their public Records, for the sole 47 | purpose of fatiguing them into compliance with his measures. 48 | 49 | He has dissolved Representative Houses repeatedly, for opposing with manly 50 | firmness his invasions on the rights of the people. 51 | 52 | He has refused for a long time, after such dissolutions, to cause others to 53 | be elected; whereby the Legislative powers, incapable of Annihilation, have 54 | returned to the People at large for their exercise; the State remaining in 55 | the mean time exposed to all the dangers of invasion from without, and 56 | convulsions within. 57 | 58 | He has endeavoured to prevent the population of these States; for that 59 | purpose obstructing the Laws for Naturalization of Foreigners; refusing to 60 | pass others to encourage their migrations hither, and raising the 61 | conditions of new Appropriations of Lands. 62 | 63 | He has obstructed the Administration of Justice, by refusing his Assent to 64 | Laws for establishing Judiciary powers. 65 | 66 | He has made Judges dependent on his Will alone, for the tenure of their 67 | offices, and the amount and payment of their salaries. 68 | 69 | He has erected a multitude of New Offices, and sent hither swarms of 70 | Officers to harrass our people, and eat out their substance. 71 | 72 | He has kept among us, in times of peace, Standing Armies without the 73 | Consent of our legislatures. 74 | 75 | He has affected to render the Military independent of and superior to the 76 | Civil power. 77 | 78 | He has combined with others to subject us to a jurisdiction foreign to our 79 | constitution, and unacknowledged by our laws; giving his Assent to their 80 | Acts of pretended Legislation. 81 | 82 | For Quartering large bodies of armed troops among us. 83 | 84 | For protecting them, by a mock Trial, from punishment for any Murders which 85 | they should commit on the Inhabitants of these States. 86 | 87 | For cutting off our Trade with all parts of the world. 88 | 89 | For imposing Taxes on us without our Consent. 90 | 91 | For depriving us in many cases, of the benefits of Trial by Jury. 92 | 93 | For transporting us beyond Seas to be tried for pretended offences. 94 | 95 | For abolishing the free System of English Laws in a neighbouring Province, 96 | establishing therein an Arbitrary government, and enlarging its Boundaries 97 | so as to render it at once an example and fit instrument for introducing 98 | the same absolute rule into these Colonies. 99 | 100 | For taking away our Charters, abolishing our most valuable Laws, and 101 | altering fundamentally the Forms of our Governments. 102 | 103 | For suspending our own Legislatures, and declaring themselves invested 104 | with power to legislate for us in all cases whatsoever. 105 | 106 | He has abdicated Government here, by declaring us out of his Protection and 107 | waging War against us. 108 | 109 | He has plundered our seas, ravaged our Coasts, burnt our towns, and 110 | destroyed the lives of our people. 111 | 112 | He is at this time transporting large Armies of foreign Mercenaries to 113 | compleat the works of death, desolation and tyranny, already begun with 114 | circumstances of Cruelty & perfidy scarcely paralleled in the most 115 | barbarous ages, and totally unworthy the Head of a civilized nation. 116 | 117 | He has constrained our fellow Citizens taken Captive on the high Seas to 118 | bear Arms against their Country, to become the executioners of their 119 | friends and Brethren, or to fall themselves by their Hands. 120 | 121 | He has excited domestic insurrections amongst us, and has endeavoured to 122 | bring on the inhabitants of our frontiers, the merciless Indian Savages, 123 | whose known rule of warfare, is an undistinguished destruction of all ages, 124 | sexes and conditions. 125 | 126 | In every stage of these Oppressions We have Petitioned for Redress in the 127 | most humble terms: Our repeated Petitions have been answered only by 128 | repeated injury. A Prince whose character is thus marked by every act which 129 | may define a Tyrant, is unfit to be the ruler of a free people. 130 | 131 | Nor have We been wanting in attentions to our Brittish brethren. We have 132 | warned them from time to time of attempts by their legislature to extend an 133 | unwarrantable jurisdiction over us. We have reminded them of the 134 | circumstances of our emigration and settlement here. We have appealed to 135 | their native justice and magnanimity, and we have conjured them by the ties 136 | of our common kindred to disavow these usurpations, which, would inevitably 137 | interrupt our connections and correspondence. They too have been deaf to 138 | the voice of justice and of consanguinity. We must, therefore, acquiesce in 139 | the necessity, which denounces our Separation, and hold them, as we hold 140 | the rest of mankind, Enemies in War, in Peace Friends. 141 | 142 | We, therefore, the Representatives of the united States of America, in 143 | General Congress, Assembled, appealing to the Supreme Judge of the world 144 | for the rectitude of our intentions, do, in the Name, and by Authority of 145 | the good People of these Colonies, solemnly publish and declare, That these 146 | United Colonies are, and of Right ought to be Free and Independent States; 147 | that they are Absolved from all Allegiance to the British Crown, and that 148 | all political connection between them and the State of Great Britain, is 149 | and ought to be totally dissolved; and that as Free and Independent States, 150 | they have full Power to levy War, conclude Peace, contract Alliances, 151 | establish Commerce, and to do all other Acts and Things which Independent 152 | States may of right do. And for the support of this Declaration, with a 153 | firm reliance on the protection of divine Providence, we mutually pledge to 154 | each other our Lives, our Fortunes and our sacred Honor. 155 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | nltk 2 | tqdm 3 | -------------------------------------------------------------------------------- /rnlp/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright © 2017-2018 StARLinG Lab 4 | # Copyright © 2019 Alexander L. Hayes 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program (at the base of this repository). If not, 18 | # see 19 | 20 | """ 21 | rnlp 22 | ==== 23 | 24 | ``pip install rnlp`` 25 | 26 | **Relational-NLP Preprocessing** (rnlp) is a Python package for converting text 27 | corpus into a set of relational facts. 28 | 29 | Designed for use with BoostSRL (https://github.com/starling-lab/BoostSRL). 30 | 31 | Motivation 32 | ========== 33 | 34 | There is no doubt that natural language processing (nlp) is a difficult task, 35 | but recent work has kindled interest in modeling the context or relations 36 | between words and their meanings in high-dimensional spaces. 37 | 38 | The intent of this package is to help with building systems which explicitly 39 | model words as a series of entities, relations, and attributes on those 40 | relations. 41 | 42 | If words are entities, then their position in a certain document is as relation 43 | between the word and a document entity, their context is a set of relations 44 | between the word entity and the other words it appears near, their attributes 45 | may be the part of speech, etc. 46 | 47 | Examples 48 | ======== 49 | 50 | .. code-block:: python 51 | 52 | import rnlp 53 | import rnlp.corpus 54 | 55 | # Get a document from the built-in corpus 56 | declaration = rnlp.corpus.declaration() 57 | 58 | # Convert the document into a set of relational facts 59 | predicates = rnlp.parse(declaration) 60 | """ 61 | 62 | from ._meta import ( 63 | __author__, 64 | __copyright__, 65 | __license__, 66 | __status__, 67 | __maintainer__, 68 | __email__, 69 | __credits__, 70 | ) 71 | from .parse import makeIdentifiers 72 | from .textprocessing import getBlocks 73 | from .textprocessing import getSentences 74 | 75 | 76 | def converter(input_string, block_size=2): 77 | """ 78 | The cli tool as a built-in function. 79 | 80 | :param input_string: A string that should be converted to a set of facts. 81 | :type input_string: str. 82 | :param blocks_size: Optional block size of sentences (Default: 2). 83 | :type block_size: int. 84 | """ 85 | 86 | sentences = getSentences(input_string) 87 | blocks = getBlocks(sentences, block_size) 88 | makeIdentifiers(blocks) 89 | -------------------------------------------------------------------------------- /rnlp/__main__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright © 2017-2018 StARLinG Lab 4 | # Copyright © 2019 Alexander L. Hayes 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program (at the base of this repository). If not, 18 | # see 19 | 20 | """ 21 | Main script for rnlp. 22 | 23 | .. code-block:: bash 24 | 25 | $ python -m rnlp --help 26 | """ 27 | 28 | import argparse 29 | import logging 30 | 31 | from .parse import makeIdentifiers 32 | from .textprocessing import getSentences 33 | from .textprocessing import getBlocks 34 | from .corpus import readCorpus 35 | 36 | from ._meta import __license__, __version__, __copyright__ 37 | 38 | LOGGER = logging.getLogger(__name__) 39 | LOGGER.setLevel(logging.INFO) 40 | 41 | PARSER = argparse.ArgumentParser( 42 | description="rnlp (v{0}): Convert text into relational facts.".format(__version__), 43 | epilog="This program is free software under the {0}. {1}".format( 44 | __license__, __copyright__ 45 | ), 46 | ) 47 | 48 | FILE_OR_DIR = PARSER.add_mutually_exclusive_group() 49 | 50 | PARSER.add_argument("-b", "--blockSize", type=int, default=2, help="Set the block size") 51 | PARSER.add_argument("-o", "--outputDir", type=str, help="Set an optional output directory") 52 | FILE_OR_DIR.add_argument( 53 | "-d", "--directory", type=str, help="Read all .txt files in directory" 54 | ) 55 | FILE_OR_DIR.add_argument("-f", "--file", type=str, help="Read from one .txt file") 56 | PARSER.add_argument("--no-logs", action="store_true", help="Specify that no logs should be created.") 57 | 58 | ARGS = PARSER.parse_args() 59 | LOG_HANDLER = logging.NullHandler() if ARGS.no_logs else logging.FileHandler("rnlp_log.log") 60 | 61 | LOG_HANDLER.setLevel(logging.INFO) 62 | FORMATTER = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 63 | LOG_HANDLER.setFormatter(FORMATTER) 64 | 65 | LOGGER.addHandler(LOG_HANDLER) 66 | LOGGER.info("Started logger.") 67 | 68 | LOGGER.info("Argument Parsing Successful.") 69 | 70 | N_BLOCKS = ARGS.blockSize 71 | LOGGER.info("blockSize specified as %s", N_BLOCKS) 72 | 73 | if ARGS.file: 74 | CHOSEN_FILE = ARGS.file 75 | elif ARGS.directory: 76 | CHOSEN_FILE = ARGS.directory 77 | else: 78 | ERROR_MESSAGE = "Error. No file or directory was specified." 79 | LOGGER.error(ERROR_MESSAGE) 80 | print(ERROR_MESSAGE) 81 | exit(1) 82 | 83 | CORPUS = readCorpus(CHOSEN_FILE) 84 | SENTENCES = getSentences(CORPUS) 85 | BLOCKS = getBlocks(SENTENCES, N_BLOCKS) 86 | makeIdentifiers(BLOCKS, outputDir=ARGS.outputDir) 87 | 88 | LOGGER.info("Reached bottom of %s.", __name__) 89 | LOGGER.info("Shutting down logger.") 90 | logging.shutdown() 91 | exit(0) 92 | -------------------------------------------------------------------------------- /rnlp/_meta.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright © 2019 Alexander L. Hayes 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program (at the base of this repository). If not, 17 | # see 18 | 19 | """ 20 | Metadata for the rnlp package. 21 | """ 22 | 23 | __author__ = "Alexander L. Hayes (@hayesall)" 24 | __copyright__ = ( 25 | "Copyright © 2017-2018 StARLinG Lab; Copyright © 2019 Alexander L. Hayes" 26 | ) 27 | __license__ = "GPL-v3" 28 | 29 | __version__ = "0.3.3.dev" 30 | __status__ = "Beta" 31 | __maintainer__ = "Alexander L. Hayes (@hayesall)" 32 | __email__ = "hayesall@iu.edu" 33 | 34 | __credits__ = [ 35 | "Kaushik Roy (@kkroy36)", 36 | "Alexander L. Hayes (@hayesall)", 37 | "Sriraam Natarajan (@boost-starai)", 38 | "Gautam Kunapuli (@gkunapuli)", 39 | "Dileep Viswanathan", 40 | "Rahul Pasunuri", 41 | ] 42 | -------------------------------------------------------------------------------- /rnlp/check_state.py: -------------------------------------------------------------------------------- 1 | _err = ( 2 | """ 3 | >>> import nltk 4 | >>> nltk.download('punkt') 5 | >>> nltk.download('stopwords') 6 | >>> nltk.download('averaged_perceptron_tagger') 7 | 8 | Visit https://rnlp.readthedocs.io/en/latest/getting_started/02_installation.html 9 | for more information. 10 | """ 11 | ) 12 | 13 | 14 | def _ensure_nltk_installed(): 15 | """ 16 | Determine if `nltk` is installed. 17 | 18 | :raises: Exception if `nltk` is not installed. 19 | """ 20 | try: 21 | import nltk 22 | except ModuleNotFoundError: 23 | raise Exception( 24 | "Unable to `import nltk` because it is not in the current environment." 25 | " Run `pip install nltk`, and then the following in an interpreter:\n" 26 | + _err 27 | ) from None 28 | 29 | 30 | def _find_nltk_module(module_name): 31 | """ 32 | Determine whether a certain `nltk` module is installed. 33 | 34 | :param module_name: Name of a module within nltk 35 | :type module name: str. 36 | 37 | :raises: Exception if the module cannot be found 38 | """ 39 | import nltk 40 | try: 41 | nltk.data.find(module_name) 42 | except LookupError as e: 43 | raise Exception( 44 | "Unable to find module '" + module_name + "'. Please run the following:\n" 45 | + _err 46 | ) from None 47 | 48 | 49 | def ensure_nltk_setup(): 50 | """Function to ensure required packages are installed.""" 51 | _ensure_nltk_installed() 52 | nltk_modules = ("tokenizers/punkt", "corpora/stopwords", "taggers/averaged_perceptron_tagger") 53 | for nltk_module in nltk_modules: 54 | _find_nltk_module(nltk_module) 55 | -------------------------------------------------------------------------------- /rnlp/corpus.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright © 2017-2018 StARLinG Lab 4 | # Copyright © 2019 Alexander L. Hayes 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program (at the base of this repository). If not, 18 | # see 19 | 20 | """ 21 | rnlp.corpus 22 | ----------- 23 | 24 | Built-in corpus and utilities for reading corpora from files. 25 | 26 | .. code-block:: python 27 | 28 | # rnlp.corpus is not imported by default. 29 | import rnlp.corpus 30 | """ 31 | 32 | from os import listdir 33 | from tqdm import tqdm 34 | 35 | 36 | def readCorpus(location): 37 | """ 38 | Returns the contents of a file or a group of files as a string. 39 | 40 | :param location: .txt file or a directory to read files from. 41 | :type location: str. 42 | 43 | :returns: A string of all contents joined together. 44 | :rtype: str. 45 | 46 | .. note:: 47 | 48 | This function takes a ``location`` on disk as a parameter. Location is 49 | assumed to be a string representing a text file or a directory. A text 50 | file is further assumed to contain ``.txt`` as a file extension while 51 | a directory may be a path. 52 | 53 | Example: 54 | 55 | .. code-block:: python 56 | 57 | from rnlp.corpus import readCorpus 58 | 59 | # If you have a text file: 60 | doi = readCorpus('files/doi.txt') 61 | 62 | # If you have multiple files to read from: 63 | corpus = readCorpus('files') 64 | """ 65 | print("Reading corpus from file(s)...") 66 | 67 | corpus = "" 68 | 69 | if ".txt" in location: 70 | with open(location) as _fp: 71 | corpus = _fp.read() 72 | else: 73 | dirFiles = listdir(location) 74 | 75 | for file in tqdm(dirFiles): 76 | with open(location + "/" + file) as _fp: 77 | corpus += _fp.read() 78 | 79 | return corpus 80 | 81 | 82 | def declaration(): 83 | """ 84 | The 'Declaration of Independence' was created before US Copyright Law, 85 | and is part of the public domain. This version captures the main text, but 86 | leaves out the signatures. 87 | 88 | The text here is based on the text available from the US National Archives 89 | https://www.archives.gov/founding-docs/declaration-transcript 90 | 91 | .. code-block:: python 92 | 93 | import rnlp 94 | from rnlp import corpus 95 | 96 | # Import the document from the corpus: 97 | doi = corpus.declaration() 98 | 99 | print(len(doi)) 100 | print(type(doi)) 101 | """ 102 | 103 | return """ 104 | In Congress, July 4, 1776. The unanimous Declaration of the thirteen united 105 | States of America, When in the Course of human events, it becomes necessary 106 | for one people to dissolve the political bands which have connected them 107 | with another, and to assume among the powers of the earth, the separate and 108 | equal station to which the Laws of Nature and of Nature's God entitle them, 109 | a decent respect to the opinions of mankind requires that they should 110 | declare the causes which impel them to the separation. 111 | 112 | We hold these truths to be self-evident, that all men are created equal, 113 | that they are endowed by their Creator with certain unalienable Rights, 114 | that among these are Life, Liberty and the pursuit of Happiness.--That to 115 | secure these rights, Governments are instituted among Men, deriving their 116 | just powers from the consent of the governed, --That whenever any Form of 117 | Government becomes destructive of these ends, it is the Right of the People 118 | to alter or to abolish it, and to institute new Government, laying its 119 | foundation on such principles and organizing its powers in such form, as 120 | to them shall seem most likely to effect their Safety and Happiness. 121 | Prudence, indeed, will dictate that Governments long established should not 122 | be changed for light and transient causes; and accordingly all experience 123 | hath shewn, that mankind are more disposed to suffer, while evils are 124 | sufferable, than to right themselves by abolishing the forms to which they 125 | are accustomed. But when a long train of abuses and usurpations, pursuing 126 | invariably the same Object evinces a design to reduce them under absolute 127 | Despotism, it is their right, it is their duty, to throw off such 128 | Government, and to provide new Guards for their future security.--Such has 129 | been the patient sufferance of these Colonies; and such is now the 130 | necessity which constrains them to alter their former Systems of 131 | Government. The history of the present King of Great Britain is a history 132 | of repeated injuries and usurpations, all having in direct object the 133 | establishment of an absolute Tyranny over these States. To prove this, let 134 | Facts be submitted to a candid world. 135 | 136 | He has refused his Assent to Laws, the most wholesome and necessary for the 137 | public good. 138 | 139 | He has forbidden his Governors to pass Laws of immediate and pressing 140 | importance, unless suspended in their operation till his Assent should 141 | be obtained; and when so suspended, he has utterly neglected to attend 142 | to them. 143 | 144 | He has refused to pass other Laws for the accommodation of large districts 145 | of people, unless those people would relinquish the right of Representation 146 | in the Legislature, a right inestimable to them and formidable to tyrants 147 | only. 148 | 149 | He has called together legislative bodies at places unusual, uncomfortable, 150 | and distant from the depository of their public Records, for the sole 151 | purpose of fatiguing them into compliance with his measures. 152 | 153 | He has dissolved Representative Houses repeatedly, for opposing with manly 154 | firmness his invasions on the rights of the people. 155 | 156 | He has refused for a long time, after such dissolutions, to cause others to 157 | be elected; whereby the Legislative powers, incapable of Annihilation, have 158 | returned to the People at large for their exercise; the State remaining in 159 | the mean time exposed to all the dangers of invasion from without, and 160 | convulsions within. 161 | 162 | He has endeavoured to prevent the population of these States; for that 163 | purpose obstructing the Laws for Naturalization of Foreigners; refusing to 164 | pass others to encourage their migrations hither, and raising the 165 | conditions of new Appropriations of Lands. 166 | 167 | He has obstructed the Administration of Justice, by refusing his Assent to 168 | Laws for establishing Judiciary powers. 169 | 170 | He has made Judges dependent on his Will alone, for the tenure of their 171 | offices, and the amount and payment of their salaries. 172 | 173 | He has erected a multitude of New Offices, and sent hither swarms of 174 | Officers to harrass our people, and eat out their substance. 175 | 176 | He has kept among us, in times of peace, Standing Armies without the 177 | Consent of our legislatures. 178 | 179 | He has affected to render the Military independent of and superior to the 180 | Civil power. 181 | 182 | He has combined with others to subject us to a jurisdiction foreign to our 183 | constitution, and unacknowledged by our laws; giving his Assent to their 184 | Acts of pretended Legislation: 185 | 186 | For Quartering large bodies of armed troops among us: 187 | 188 | For protecting them, by a mock Trial, from punishment for any Murders which 189 | they should commit on the Inhabitants of these States: 190 | 191 | For cutting off our Trade with all parts of the world: 192 | 193 | For imposing Taxes on us without our Consent: 194 | 195 | For depriving us in many cases, of the benefits of Trial by Jury: 196 | 197 | For transporting us beyond Seas to be tried for pretended offences 198 | 199 | For abolishing the free System of English Laws in a neighbouring Province, 200 | establishing therein an Arbitrary government, and enlarging its Boundaries 201 | so as to render it at once an example and fit instrument for introducing 202 | the same absolute rule into these Colonies: 203 | 204 | For taking away our Charters, abolishing our most valuable Laws, and 205 | altering fundamentally the Forms of our Governments: 206 | 207 | For suspending our own Legislatures, and declaring themselves invested 208 | with power to legislate for us in all cases whatsoever. 209 | 210 | He has abdicated Government here, by declaring us out of his Protection and 211 | waging War against us. 212 | 213 | He has plundered our seas, ravaged our Coasts, burnt our towns, and 214 | destroyed the lives of our people. 215 | 216 | He is at this time transporting large Armies of foreign Mercenaries to 217 | compleat the works of death, desolation and tyranny, already begun with 218 | circumstances of Cruelty & perfidy scarcely paralleled in the most 219 | barbarous ages, and totally unworthy the Head of a civilized nation. 220 | 221 | He has constrained our fellow Citizens taken Captive on the high Seas to 222 | bear Arms against their Country, to become the executioners of their 223 | friends and Brethren, or to fall themselves by their Hands. 224 | 225 | He has excited domestic insurrections amongst us, and has endeavoured to 226 | bring on the inhabitants of our frontiers, the merciless Indian Savages, 227 | whose known rule of warfare, is an undistinguished destruction of all ages, 228 | sexes and conditions. 229 | 230 | In every stage of these Oppressions We have Petitioned for Redress in the 231 | most humble terms: Our repeated Petitions have been answered only by 232 | repeated injury. A Prince whose character is thus marked by every act which 233 | may define a Tyrant, is unfit to be the ruler of a free people. 234 | 235 | Nor have We been wanting in attentions to our Brittish brethren. We have 236 | warned them from time to time of attempts by their legislature to extend an 237 | unwarrantable jurisdiction over us. We have reminded them of the 238 | circumstances of our emigration and settlement here. We have appealed to 239 | their native justice and magnanimity, and we have conjured them by the ties 240 | of our common kindred to disavow these usurpations, which, would inevitably 241 | interrupt our connections and correspondence. They too have been deaf to 242 | the voice of justice and of consanguinity. We must, therefore, acquiesce in 243 | the necessity, which denounces our Separation, and hold them, as we hold 244 | the rest of mankind, Enemies in War, in Peace Friends. 245 | 246 | We, therefore, the Representatives of the united States of America, in 247 | General Congress, Assembled, appealing to the Supreme Judge of the world 248 | for the rectitude of our intentions, do, in the Name, and by Authority of 249 | the good People of these Colonies, solemnly publish and declare, That these 250 | United Colonies are, and of Right ought to be Free and Independent States; 251 | that they are Absolved from all Allegiance to the British Crown, and that 252 | all political connection between them and the State of Great Britain, is 253 | and ought to be totally dissolved; and that as Free and Independent States, 254 | they have full Power to levy War, conclude Peace, contract Alliances, 255 | establish Commerce, and to do all other Acts and Things which Independent 256 | States may of right do. And for the support of this Declaration, with a 257 | firm reliance on the protection of divine Providence, we mutually pledge to 258 | each other our Lives, our Fortunes and our sacred Honor. 259 | """ 260 | -------------------------------------------------------------------------------- /rnlp/parse.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright © 2017-2018 StARLinG Lab 5 | # Copyright © 2019 Alexander L. Hayes 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program (at the base of this repository). If not, 19 | # see 20 | 21 | """ 22 | rnlp.parse 23 | ---------- 24 | """ 25 | import rnlp.check_state as check_state 26 | check_state.ensure_nltk_setup() 27 | 28 | import os 29 | import string 30 | import nltk 31 | from tqdm import tqdm 32 | 33 | __all__ = ["makeIdentifiers"] 34 | 35 | def __getOutputFile(outputDir, fileName): 36 | if outputDir is None: 37 | # If no outputDir passed in, set to the current directory 38 | outputDir = os.getcwd() 39 | elif not os.path.isdir(outputDir): 40 | # Ensure it exists 41 | os.makedirs(outputDir) 42 | 43 | return os.path.join(outputDir, fileName) 44 | 45 | 46 | def _writeBlock(block, blockID, outputDir=None): 47 | """Writes the blocks to a file with blockID.""" 48 | outputFile = __getOutputFile(outputDir, "blockIDs.txt") 49 | with open(outputFile, "a") as fp: 50 | fp.write("blockID: " + str(blockID) + "\n") 51 | sentences = ",".join(block) 52 | fp.write("block sentences: " + sentences + "\n") 53 | fp.write("\n") 54 | 55 | 56 | def _writeSentenceInBlock(sentence, blockID, sentenceID, outputDir=None): 57 | """Writes the sentence in a block to a file with the id.""" 58 | outputFile = __getOutputFile(outputDir, "sentenceIDs.txt") 59 | with open(outputFile, "a") as fp: 60 | fp.write("sentenceID: " + str(blockID) + "_" + str(sentenceID) + "\n") 61 | fp.write("sentence string: " + sentence+"\n") 62 | fp.write("\n") 63 | 64 | 65 | def _writeWordFromSentenceInBlock(word, blockID, sentenceID, wordID, outputDir=None): 66 | """Writes the word from a sentence in a block to a file with the id.""" 67 | outputFile = __getOutputFile(outputDir, "wordIDs.txt") 68 | with open(outputFile, "a") as fp: 69 | fp.write("wordID: " + str(blockID) + "_" + str(sentenceID) + "_" + str(wordID) + "\n") 70 | fp.write("wordString: " + word + "\n") 71 | fp.write("\n") 72 | 73 | 74 | def _writeFact(predicateString, outputDir=None): 75 | """writes the fact to facts file.""" 76 | outputFile = __getOutputFile(outputDir, "facts.txt") 77 | with open(outputFile, "a") as fp: 78 | fp.write(predicateString + "\n") 79 | 80 | 81 | def _writeBk(target="sentenceContainsTarget(+SID,+WID).", treeDepth="3", 82 | nodeSize="3", numOfClauses="8", outputDir=None): 83 | """ 84 | Writes a background file to disk. 85 | 86 | :param target: Target predicate with modes. 87 | :type target: str. 88 | :param treeDepth: Depth of the tree. 89 | :type treeDepth: str. 90 | :param nodeSize: Maximum size of each node in the tree. 91 | :type nodeSize: str. 92 | :param numOfClauses: Number of clauses in total. 93 | :type numOfClauses: str. 94 | """ 95 | outputFile = __getOutputFile(outputDir, "bk.txt") 96 | with open(outputFile, "a") as fp: 97 | 98 | fp.write("useStdLogicVariables: true\n") 99 | 100 | fp.write("setParam: treeDepth=" + str(treeDepth) + ".\n") 101 | fp.write("setParam: nodeSize=" + str(nodeSize) + ".\n") 102 | fp.write("setParam: numOfClauses=" + str(numOfClauses) + ".\n") 103 | 104 | fp.write("mode: nextSentenceInBlock(+BID,+SID,-SID).\n") 105 | fp.write("mode: nextSentenceInBlock(+BID,-SID,+SID).\n") 106 | fp.write("mode: earlySentenceInBlock(+BID,-SID).\n") 107 | fp.write("mode: midWaySentenceInBlock(+BID,-SID).\n") 108 | fp.write("mode: lateSentenceInBlock(+BID,-SID).\n") 109 | fp.write("mode: sentenceInBlock(-SID,+BID).\n") 110 | fp.write("mode: wordString(+WID,#WSTR).\n") 111 | fp.write("mode: partOfSpeechTag(+WID,#WPOS).\n") 112 | fp.write("mode: nextWordInSentence(+SID,+WID,-WID).\n") 113 | fp.write("mode: earlyWordInSentence(+SID,-WID).\n") 114 | fp.write("mode: midWayWordInSentence(+SID,-WID).\n") 115 | fp.write("mode: lateWordInSentence(+SID,-WID).\n") 116 | fp.write("mode: wordInSentence(-WID,+SID).\n") 117 | 118 | fp.write("mode: " + target + "\n") 119 | 120 | 121 | def makeIdentifiers(blocks, target="sentenceContainsTarget(+SID,+WID).", 122 | treeDepth="3", nodeSize="3", numOfClauses="8", outputDir=None): 123 | """ 124 | Make unique identifiers for components of the block and write to files. 125 | 126 | :param blocks: Blocks of sentences (likely the output of 127 | ``textprocessing.getBlocks``). 128 | :type blocks: list 129 | :param target: Target to write to the background file (another option might 130 | be ``blockContainsTarget(+BID,+SID).``). 131 | :type target: str. 132 | :param treeDepth: Depth of the tree. 133 | :type treeDepth: str. 134 | :param nodeSize: Maximum size of each node in the tree. 135 | :type nodeSize: str. 136 | :param numOfClauses: Number of clauses in total. 137 | :type numOfClauses: str. 138 | :param output: Optional directory to pass in for output 139 | type output: str. 140 | 141 | .. note:: This is a function that writes *facts*, presently there is no 142 | way to distinguish between these and positive/negatives examples. 143 | 144 | Example: 145 | 146 | .. code-block:: python 147 | 148 | from rnlp.textprocessing import getSentences 149 | from rnlp.textprocessing import getBlocks 150 | from rnlp.parse import makeIdentifiers 151 | 152 | example = "Hello there. How are you? I am fine." 153 | 154 | sentences = getSentences(example) 155 | # ['Hello there', 'How are you', 'I am fine'] 156 | 157 | blocks = getBlocks(sentences, 2) 158 | # with 1: [['Hello there'], ['How are you'], ['I am fine']] 159 | # with 2: [['Hello there', 'How are you'], ['I am fine']] 160 | # with 3: [['Hello there', 'How are you', 'I am fine']] 161 | 162 | makeIdentifiers(blocks) 163 | # 100%|██████████████████████| 2/2 [00:00<00:00, 18.49it/s] 164 | """ 165 | 166 | blockID, sentenceID, wordID = 1, 0, 0 167 | print("Creating background file...") 168 | 169 | _writeBk( 170 | target=target, 171 | treeDepth=treeDepth, 172 | nodeSize=nodeSize, 173 | numOfClauses=numOfClauses, 174 | outputDir=outputDir 175 | ) 176 | 177 | print("Creating identifiers from the blocks...") 178 | 179 | nBlocks = len(blocks) 180 | for block in tqdm(blocks): 181 | 182 | _writeBlock(block, blockID, outputDir) 183 | 184 | sentenceID = 1 185 | nSentences = len(block) 186 | beginning = nSentences/float(3) 187 | ending = (2*nSentences)/float(3) 188 | 189 | for sentence in block: 190 | 191 | if sentenceID < nSentences: 192 | # mode: nextSentenceInBlock(blockID, sentenceID, sentenceID). 193 | ps = "nextSentenceInBlock(" + str(blockID) + "," + \ 194 | str(blockID) + "_" + str(sentenceID) + "," + \ 195 | str(blockID) + "_" + str(sentenceID+1) + ")." 196 | _writeFact(ps, outputDir) 197 | 198 | if sentenceID < beginning: 199 | # mode: earlySentenceInBlock(blockID, sentenceID). 200 | ps = "earlySentenceInBlock(" + str(blockID) + "," + \ 201 | str(blockID) + "_" + str(sentenceID) + ")." 202 | _writeFact(ps, outputDir) 203 | elif sentenceID > ending: 204 | # mode: lateSentenceInBlock(blockID, sentenceID). 205 | ps = "lateSentenceInBlock(" + str(blockID) + "," + \ 206 | str(blockID) + "_" + str(sentenceID) + ")." 207 | _writeFact(ps, outputDir) 208 | else: 209 | # mode: midWaySentenceInBlock(blockID, sentenceID). 210 | ps = "earlySentenceInBlock(" + str(blockID) + "," + \ 211 | str(blockID) + "_" + str(sentenceID) + ")." 212 | _writeFact(ps, outputDir) 213 | 214 | # mode: sentenceInBlock(sentenceID, blockID). 215 | ps = "sentenceInBlock(" + str(blockID) + "_" + str(sentenceID) + \ 216 | "," + str(blockID) + ")." 217 | _writeFact(ps, outputDir) 218 | _writeSentenceInBlock(sentence, blockID, sentenceID, outputDir) 219 | 220 | wordID = 1 221 | tokens = nltk.word_tokenize(sentence) 222 | nWords = len(tokens) 223 | wBeginning = nWords/float(3) 224 | wEnding = (2*nWords)/float(3) 225 | 226 | for word in tokens: 227 | 228 | # mode: wordString(wordID, #str). 229 | ps = "wordString(" + str(blockID) + "_" + str(sentenceID) + \ 230 | "_" + str(wordID) + "," + "'" + str(word) + "')." 231 | _writeFact(ps, outputDir) 232 | 233 | # mode: partOfSpeechTag(wordID, #POS). 234 | POS = nltk.pos_tag([word])[0][1] 235 | ps = "partOfSpeech(" + str(blockID) + "_" + str(sentenceID) + \ 236 | "_" + str(wordID) + "," + '"' + str(POS) + '").' 237 | _writeFact(ps, outputDir) 238 | 239 | # mode: nextWordInSentence(sentenceID, wordID, wordID). 240 | if wordID < nWords: 241 | ps = "nextWordInSentence(" + str(blockID) + "_" + \ 242 | str(sentenceID) + "," + str(blockID) + "_" + \ 243 | str(sentenceID) + "_" + str(wordID) + "," + \ 244 | str(blockID) + "_" + str(sentenceID) + "_" + \ 245 | str(wordID+1) + ")." 246 | _writeFact(ps, outputDir) 247 | 248 | if wordID < wBeginning: 249 | # mode: earlyWordInSentence(sentenceID, wordID). 250 | ps = "earlyWordInSentence(" + str(blockID) + "_" + \ 251 | str(sentenceID) + "," + str(blockID) + "_" + \ 252 | str(sentenceID) + "_" + str(wordID) + ")." 253 | _writeFact(ps, outputDir) 254 | elif wordID > wEnding: 255 | # mode: lateWordInSentence(sentenceID< wordID). 256 | ps = "lateWordInSentence(" + str(blockID) + "_" + \ 257 | str(sentenceID) + "," + str(blockID) + "_" + \ 258 | str(sentenceID) + "_" + str(wordID) + ")." 259 | _writeFact(ps, outputDir) 260 | else: 261 | # mode: midWayWordInSentence(sentenceID, wordID). 262 | ps = "midWayWordInSentence(" + str(blockID) + "_" + \ 263 | str(sentenceID) + "," + str(blockID) + "_" + \ 264 | str(sentenceID) + "_" + str(wordID) + ")." 265 | _writeFact(ps, outputDir) 266 | 267 | # mode: wordInSentence(wordID, sentenceID). 268 | ps = "wordInSentence(" + str(blockID) + "_" + \ 269 | str(sentenceID) + "_" + str(wordID) + "," + \ 270 | str(blockID) + "_" + str(sentenceID) + ")." 271 | _writeFact(ps, outputDir) 272 | _writeWordFromSentenceInBlock(word, blockID, sentenceID, wordID, outputDir) 273 | wordID += 1 274 | sentenceID += 1 275 | blockID += 1 276 | -------------------------------------------------------------------------------- /rnlp/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/rnlp/tests/__init__.py -------------------------------------------------------------------------------- /rnlp/tests/requirements.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | pytest 3 | pytest-cov 4 | unittest2 5 | nltk 6 | tqdm 7 | -------------------------------------------------------------------------------- /rnlp/tests/rnlptests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srlearn/rnlp/cc925b0c2f51374b4fe1890e52bc044fd5ea9037/rnlp/tests/rnlptests/__init__.py -------------------------------------------------------------------------------- /rnlp/tests/rnlptests/test_converter.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2018 StARLinG Lab 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program (at the base of this repository). If not, 15 | # see 16 | 17 | import hashlib 18 | import os 19 | import unittest 20 | 21 | from rnlp import converter 22 | from rnlp.corpus import declaration 23 | 24 | 25 | class converterTest(unittest.TestCase): 26 | """ 27 | This performs a similar test to test_parse.py, but uses rnlp.converter. 28 | """ 29 | def __init__(self, *args, **kwargs): 30 | super(converterTest, self).__init__(*args, **kwargs) 31 | 32 | self._path = os.getcwd() 33 | self._fileSet = [ 34 | "wordIDs.txt", 35 | "sentenceIDs.txt", 36 | "blockIDs.txt", 37 | "facts.txt", 38 | "bk.txt" 39 | ] 40 | 41 | def tearDown(self): 42 | """ 43 | Removes files created by ``parse.makeIdentifiers``, since the current 44 | version appends to the end of the files each time the function runs. 45 | """ 46 | for f in self._fileSet: 47 | f = os.path.join(self._path, f) 48 | if os.path.isfile(f): 49 | os.remove(f) 50 | 51 | def EqualFileContents(self, fileName, expectedHash): 52 | """ 53 | Open ``fileName`` and return true if the list ``expectedContents`` 54 | match the contents of the file. 55 | """ 56 | 57 | with open(fileName) as f: 58 | contents = f.read() 59 | 60 | trueHash = hashlib.md5(contents.encode("utf-8")).hexdigest() 61 | 62 | return trueHash == expectedHash 63 | 64 | def runner(self, example, blockLength, hashlist): 65 | """ 66 | Creates identifiers with makeIdentifiers, and asserts that 67 | the md5 hashes match. 68 | 69 | example: str. 70 | blockLength: int. 71 | hashlist: list of five hash values. 72 | """ 73 | 74 | converter(example, blockLength) 75 | 76 | for index, fileName in enumerate(self._fileSet): 77 | fileName = os.path.join(self._path, fileName) 78 | self.assertTrue(self.EqualFileContents(fileName, hashlist[index])) 79 | 80 | def test_makeIdentifiers_1(self): 81 | self.runner("Hello there. How are you?", 1, 82 | ["bbaccb43cf22eeea851df721a40fddb7", 83 | "60ffc99bc55eaab87b74d77557164bd0", 84 | "41f2b5849b50502d31152bc20ec9f81d", 85 | "53e96b0214838323def0375b0ac40023", 86 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 87 | 88 | def test_makeIdentifiers_2(self): 89 | self.runner("A B. C D. E F.", 1, ["87a3b6464acc41ca7939fe6e2062a60b", 90 | "049b7a05061ed1478669c23e8bd946c6", 91 | "62131ea41b1bf0363d61c34a72d6b34c", 92 | "1a4273067a5f959ed78a6f571a63ae1c", 93 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 94 | 95 | def test_makeIdentifiers_3(self): 96 | self.runner(declaration(), 1, ["3beca96390f114e4bb5513aed359e090", 97 | "3e7168dc0ecfc76b1710edb8fb147d41", 98 | "3778793bd861a1bc658c2b55bdc2eaf3", 99 | "8ec3d7d72ffedf1740f04b838a7164b6", 100 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 101 | 102 | def test_makeIdentifiers_4(self): 103 | self.runner(declaration(), 2, ["9ef701f7a5c1da8eb8d0e87ba63025f6", 104 | "28f7f057e5a5a9a66a0d37686716c9f6", 105 | "56d6a375bb36a4e68b1a1a6e3d194fda", 106 | "1af5996e085f3ba7fe906992ee723513", 107 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 108 | 109 | def test_makeIdentifiers_5(self): 110 | self.runner(declaration(), 3, ["7c653cc6e226acfb685144581bec0c10", 111 | "06441a60380e2b3915ee9de25019df9f", 112 | "368f35fe0a34ba6984ed4e977cca3687", 113 | "6ce50160bc795d4a8476916d4e688a51", 114 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 115 | -------------------------------------------------------------------------------- /rnlp/tests/rnlptests/test_parse.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2018 StARLinG Lab 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program (at the base of this repository). If not, 15 | # see 16 | 17 | import hashlib 18 | import os 19 | import unittest 20 | 21 | from rnlp.corpus import declaration 22 | from rnlp.parse import makeIdentifiers 23 | from rnlp.textprocessing import getBlocks, getSentences 24 | import rnlp 25 | 26 | class makeIdentifiersTest(unittest.TestCase): 27 | """ 28 | makeIdentifiers is not elegant to test in practice (since it does a 29 | large amount of i/o). 30 | """ 31 | def __init__(self, *args, **kwargs): 32 | super(makeIdentifiersTest, self).__init__(*args, **kwargs) 33 | 34 | self._path = os.getcwd() 35 | self._fileSet = [ 36 | "wordIDs.txt", 37 | "sentenceIDs.txt", 38 | "blockIDs.txt", 39 | "facts.txt", 40 | "bk.txt" 41 | ] 42 | 43 | def tearDown(self): 44 | """ 45 | Removes files created by ``parse.makeIdentifiers``, since the current 46 | version appends to the end of the files each time the function runs. 47 | """ 48 | for f in self._fileSet: 49 | f = os.path.join(self._path, f) 50 | if os.path.isfile(f): 51 | os.remove(f) 52 | 53 | self._path = os.getcwd() 54 | 55 | def EqualFileContents(self, fileName, expectedHash): 56 | """ 57 | Open ``fileName`` and return true if the list ``expectedContents`` 58 | match the contents of the file. 59 | """ 60 | 61 | with open(fileName) as f: 62 | contents = f.read() 63 | 64 | trueHash = hashlib.md5(contents.encode("utf-8")).hexdigest() 65 | 66 | return trueHash == expectedHash 67 | 68 | def runner(self, example, blockLength, hashlist): 69 | """ 70 | Creates identifiers with makeIdentifiers, and asserts that 71 | the md5 hashes match. 72 | 73 | example: str. 74 | blockLength: int. 75 | hashlist: list of five hash values. 76 | """ 77 | 78 | sentences = getSentences(example) 79 | blocks = getBlocks(sentences, blockLength) 80 | makeIdentifiers(blocks, outputDir=self._path) 81 | 82 | for index, fileName in enumerate(self._fileSet): 83 | fileName = os.path.join(self._path, fileName) 84 | self.assertTrue(self.EqualFileContents(fileName, hashlist[index])) 85 | 86 | def test_makeIdentifiers_1(self): 87 | self.runner("Hello there. How are you?", 1, 88 | ["bbaccb43cf22eeea851df721a40fddb7", 89 | "60ffc99bc55eaab87b74d77557164bd0", 90 | "41f2b5849b50502d31152bc20ec9f81d", 91 | "53e96b0214838323def0375b0ac40023", 92 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 93 | 94 | def test_makeIdentifiers_2(self): 95 | self.runner("A B. C D. E F.", 1, ["87a3b6464acc41ca7939fe6e2062a60b", 96 | "049b7a05061ed1478669c23e8bd946c6", 97 | "62131ea41b1bf0363d61c34a72d6b34c", 98 | "1a4273067a5f959ed78a6f571a63ae1c", 99 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 100 | 101 | def test_makeIdentifiers_3(self): 102 | self.runner(declaration(), 1, ["3beca96390f114e4bb5513aed359e090", 103 | "3e7168dc0ecfc76b1710edb8fb147d41", 104 | "3778793bd861a1bc658c2b55bdc2eaf3", 105 | "8ec3d7d72ffedf1740f04b838a7164b6", 106 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 107 | 108 | def test_makeIdentifiers_4(self): 109 | self.runner(declaration(), 2, ["9ef701f7a5c1da8eb8d0e87ba63025f6", 110 | "28f7f057e5a5a9a66a0d37686716c9f6", 111 | "56d6a375bb36a4e68b1a1a6e3d194fda", 112 | "1af5996e085f3ba7fe906992ee723513", 113 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 114 | 115 | def test_makeIdentifiers_5(self): 116 | self.runner(declaration(), 3, ["7c653cc6e226acfb685144581bec0c10", 117 | "06441a60380e2b3915ee9de25019df9f", 118 | "368f35fe0a34ba6984ed4e977cca3687", 119 | "6ce50160bc795d4a8476916d4e688a51", 120 | "f8f91289b8db5fa0270ffc0b0c94bd09"]) 121 | 122 | def test_makeIdentifiers_outputDir(self): 123 | self._path = "test" 124 | self.test_makeIdentifiers_1() 125 | 126 | def test_makeIdentifiers_nestedOutputDir(self): 127 | self._path = "test/test" 128 | self.test_makeIdentifiers_1() 129 | -------------------------------------------------------------------------------- /rnlp/tests/rnlptests/test_textprocessing.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2018 StARLinG Lab 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program (at the base of this repository). If not, 15 | # see 16 | 17 | import unittest 18 | 19 | from rnlp import textprocessing 20 | 21 | 22 | class removePunctuationTest(unittest.TestCase): 23 | """ 24 | removePunctuation uses strip() to remove characters at the end. 25 | """ 26 | 27 | def test_removePunctuation_1(self): 28 | sent = ".?:" 29 | self.assertEqual(textprocessing._removePunctuation(sent), "") 30 | 31 | def test_removePunctuation_2(self): 32 | sent = "helloself." 33 | self.assertEqual(textprocessing._removePunctuation(sent), "helloself") 34 | 35 | def test_removePunctuation_3(self): 36 | sent = "Hi.There" 37 | self.assertEqual(textprocessing._removePunctuation(sent), "HiThere") 38 | 39 | def test_removePunctuation_4(self): 40 | import string 41 | sent = string.punctuation 42 | self.assertEqual(textprocessing._removePunctuation(sent), "") 43 | 44 | def test_removePunctuation_5(self): 45 | sent = "(def add1 (lambda (n)) + n 1)" 46 | self.assertEqual(textprocessing._removePunctuation(sent), 47 | "def add1 lambda n n 1") 48 | 49 | class removeStopwordsTest(unittest.TestCase): 50 | 51 | def test_removeStopwords_1(self): 52 | sent = "and then there were none".split() 53 | self.assertEqual(textprocessing._removeStopwords(sent), 54 | ["none"]) 55 | 56 | def test_removeStopwords_2(self): 57 | sent = "no stopwords here".split() 58 | self.assertEqual(textprocessing._removeStopwords(sent), 59 | ["stopwords"]) 60 | 61 | def test_removeStopwords_3(self): 62 | from nltk.corpus import stopwords 63 | sent = stopwords.words("english") 64 | self.assertEqual(textprocessing._removeStopwords(sent), []) 65 | 66 | def test_removeStopwords_4(self): 67 | sent = "finally".split() 68 | self.assertEqual(textprocessing._removeStopwords(sent), ["finally"]) 69 | 70 | class getSentencesTest(unittest.TestCase): 71 | 72 | def test_getSentences_1(self): 73 | sents = "Hi there. Hello there. Bye now." 74 | self.assertEqual(textprocessing.getSentences(sents), 75 | ["Hi there", "Hello there", "Bye now"]) 76 | 77 | def test_getSentences_2(self): 78 | sents = "We hold these truths to be self evident." 79 | self.assertEqual(textprocessing.getSentences(sents), 80 | ["We hold these truths to be self evident"]) 81 | 82 | def test_getSentences_3(self): 83 | sents = "One. Two three. Three. Four" 84 | self.assertEqual(textprocessing.getSentences(sents), 85 | ["One", "Two three", "Three", "Four"]) 86 | 87 | class getBlocks(unittest.TestCase): 88 | 89 | def test_getBlocks_1(self): 90 | sents = textprocessing.getSentences("Hello. How are you? I am fine.") 91 | self.assertEqual(textprocessing.getBlocks(sents, 1), 92 | [["Hello"], ["How are you"], ["I am fine"]]) 93 | self.assertEqual(textprocessing.getBlocks(sents, 2), 94 | [["Hello", "How are you"], ["I am fine"]]) 95 | self.assertEqual(textprocessing.getBlocks(sents, 3), 96 | [["Hello", "How are you", "I am fine"]]) 97 | 98 | def test_getBlocks_2(self): 99 | sents = textprocessing.getSentences("""How do you document real life? 100 | When real life's getting more like fiction each day? Headlines, 101 | breadlines blow my mind, and now this deadline.""") 102 | self.assertEqual(textprocessing.getBlocks(sents, 1), 103 | [["How do you document real life"], 104 | ["When real lifes getting more like fiction each day"], 105 | ["Headlines\n breadlines blow my mind and now this deadline"]]) 106 | 107 | def test_getBlocks_3(self): 108 | sents = textprocessing.getSentences( 109 | "RENT. How do you write a song when the chords sound wrong?") 110 | self.assertEqual(textprocessing.getBlocks(sents, 1), 111 | [["RENT"], ["How do you write a song when the chords sound wrong"]]) 112 | self.assertEqual(textprocessing.getBlocks(sents, 2), 113 | [["RENT", "How do you write a song when the chords sound wrong"]]) 114 | -------------------------------------------------------------------------------- /rnlp/tests/tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | if __name__ == '__main__': 4 | """ 5 | Testing module for ``rnlp``, to be ran from the base of the repository. 6 | 7 | .. code-block:: bash 8 | 9 | python rnlp/tests/tests.py 10 | 11 | Verbosity may be explicitly set by passing an integer with the ``-v`` 12 | flag. The value will be passed into the unittest.TextTestRunner, so 13 | integers higher than 1 will lead to more verbose outputs. 14 | 15 | .. code-block:: bash 16 | 17 | python rnlp/tests/tests.py -v 2 18 | 19 | Individual modules may be tested with unittest via the command line. 20 | 21 | .. code-block:: bash 22 | 23 | python -m unittest rnlp/tests/rnlptests/test_parse.py 24 | ... 25 | -------------------------------------------------- 26 | Ran 3 tests in 0.008s 27 | 28 | OK 29 | """ 30 | 31 | import argparse 32 | 33 | parser = argparse.ArgumentParser() 34 | parser.add_argument("-v", "--verbose", 35 | default=1, 36 | type=int) 37 | args = parser.parse_args() 38 | 39 | testsuite = unittest.TestLoader().discover(".") 40 | runner = unittest.TextTestRunner(verbosity=args.verbose) 41 | 42 | results = runner.run(testsuite) 43 | if results.failures or results.errors: 44 | raise(Exception("Encountered errors during runner.run")) 45 | -------------------------------------------------------------------------------- /rnlp/textprocessing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright © 2017-2018 StARLinG Lab 4 | # Copyright © 2019 Alexander L. Hayes 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program (at the base of this repository). If not, 18 | # see 19 | 20 | """ 21 | textprocessing 22 | -------------- 23 | 24 | A set of functions for normalizing text, with options for stemming, 25 | stopping, removing punctuation, etc. 26 | 27 | Document Hierarchy 28 | ------------------ 29 | 30 | A corpus is a collection of documents. 31 | A document is a collection of chapters. 32 | A chapter is a collection of paragraphs. 33 | A paragraph is a collection of sentences. 34 | A sentence is a collection of words. 35 | A word is a collection of letters... 36 | 37 | The depth of reasoning probably depends on the domain you are working on. 38 | """ 39 | 40 | import rnlp.check_state as check_state 41 | check_state.ensure_nltk_setup() 42 | 43 | import string 44 | from nltk import sent_tokenize 45 | from nltk.corpus import stopwords 46 | 47 | PUNCTUATION = string.punctuation 48 | STOPWORDS = stopwords.words("english") 49 | 50 | 51 | def _removePunctuation(text_string): 52 | """ 53 | Removes punctuation symbols from a string. 54 | 55 | :param text_string: A string. 56 | :type text_string: str. 57 | 58 | :returns: The input ``text_string`` with punctuation symbols removed. 59 | :rtype: str. 60 | 61 | >>> from rnlp.textprocessing import __removePunctuation 62 | >>> example = 'Hello, World!' 63 | >>> __removePunctuation(example) 64 | 'Hello World' 65 | """ 66 | try: 67 | return text_string.translate(None, PUNCTUATION) 68 | except TypeError: 69 | return text_string.translate(str.maketrans("", "", PUNCTUATION)) 70 | 71 | 72 | def _removeStopwords(text_list): 73 | """ 74 | Removes stopwords contained in a list of words. 75 | 76 | :param text_string: A list of strings. 77 | :type text_string: list. 78 | 79 | :returns: The input ``text_list`` with stopwords removed. 80 | :rtype: list 81 | """ 82 | 83 | output_list = [] 84 | 85 | for word in text_list: 86 | if word.lower() not in STOPWORDS: 87 | output_list.append(word) 88 | 89 | return output_list 90 | 91 | 92 | def getBlocks(sentences, n_blocks): 93 | """ 94 | Get blocks of n sentences together. 95 | 96 | :param sentences: List of strings where each string is a sentence. 97 | :type sentences: list 98 | :param n_blocks: Maximum blocksize for sentences, i.e. a block will be 99 | composed of ``n_blocks`` sentences. 100 | :type n_blocks: int. 101 | 102 | :returns: Blocks of n sentences. 103 | :rtype: list-of-lists 104 | 105 | .. code-block:: python 106 | 107 | import rnlp 108 | 109 | example = "Hello there. How are you? I am fine." 110 | 111 | sentences = rnlp.getSentences(example) 112 | # ['Hello there', 'How are you', 'I am fine'] 113 | 114 | blocks = rnlp.getBlocks(sentences, 2) 115 | # with 1: [['Hello there'], ['How are you'], ['I am fine']] 116 | # with 2: [['Hello there', 'How are you'], ['I am fine']] 117 | # with 3: [['Hello there', 'How are you', 'I am fine']] 118 | """ 119 | blocks = [] 120 | for i in range(0, len(sentences), n_blocks): 121 | blocks.append(sentences[i : (i + n_blocks)]) 122 | return blocks 123 | 124 | 125 | def getSentences(text_string): 126 | """ 127 | Tokenizes the corpus into sentences, removing punctuation as it does so. 128 | 129 | :param text_string: A string. 130 | :type text_string: str. 131 | 132 | :returns: A list of string sentences with punctuation removed. 133 | :rtype: list 134 | 135 | .. code-block:: python 136 | 137 | import rnlp 138 | 139 | example = "Hello there. How are you? I am fine." 140 | sentences = rnlp.getSentences(example) 141 | # ['Hello there', 'How are you', 'I am fine'] 142 | """ 143 | return [_removePunctuation(s) for s in sent_tokenize(text_string)] 144 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | license_file = LICENSE 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Setup file for rnlp 3 | """ 4 | 5 | from setuptools import setup 6 | from setuptools import find_packages 7 | 8 | from codecs import open 9 | from os import path 10 | 11 | # Get __version__, __license__ and others from _meta.py 12 | with open(path.join("rnlp", "_meta.py")) as f: 13 | exec(f.read()) 14 | 15 | here = path.abspath(path.dirname(__file__)) 16 | 17 | # Get the long description from the README.md 18 | with open(path.join(here, "README.rst"), encoding="utf-8") as f: 19 | long_description = f.read() 20 | 21 | setup( 22 | name="rnlp", 23 | version=__version__, 24 | license=__license__, 25 | description="Converts text corpora into a set of relational facts.", 26 | long_description=long_description, 27 | url="https://github.com/hayesall/rnlp", 28 | author=__author__, 29 | author_email=__email__, 30 | classifiers=[ 31 | "Development Status :: 4 - Beta", 32 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 33 | "Intended Audience :: Science/Research", 34 | "Operating System :: POSIX :: Linux", 35 | "Operating System :: Microsoft :: Windows :: Windows 10", 36 | "Programming Language :: Python :: 3.4", 37 | "Programming Language :: Python :: 3.5", 38 | "Programming Language :: Python :: 3.6", 39 | "Programming Language :: Python :: 3.7", 40 | ], 41 | keywords="nlp", 42 | project_urls={ 43 | "Source": "https://github.com/hayesall/rnlp", 44 | "Tracker": "https://github.com/hayesall/rnlp/issues", 45 | }, 46 | packages=find_packages(exclude=["tests"]), 47 | install_requires=["nltk", "tqdm", "joblib"], 48 | setup_requires=["nltk"], 49 | ) 50 | --------------------------------------------------------------------------------