├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── .gitignore ├── .travis.yml ├── LICENSE.md ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── conf.py └── index.rst ├── preprocessor ├── __init__.py ├── api.py ├── defines.py ├── enum.py ├── parse.py ├── preprocess.py └── utils.py ├── requirements ├── dev-requirements.txt └── requirements.txt ├── setup.py └── tests ├── __init__.py ├── artifacts ├── clean_file_sample.json └── clean_file_sample.txt ├── test_api.py ├── test_clean_numbers.py └── test_utils.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. macOS] 28 | - Python Version: [e.g. 3.7.3] 29 | - preprocessor version [e.g. 0.6.0] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | tests/artifacts/* 3 | !tests/artifacts/clean_file_sample.json 4 | !tests/artifacts/clean_file_sample.txt 5 | .DS_Store 6 | .python-version 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | docs/*build/ 11 | # C extensions 12 | *.so 13 | .idea/ 14 | # Distribution / packaging 15 | .Python 16 | env/ 17 | venv/ 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *,cover 52 | .hypothesis/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | 61 | # Sphinx documentation 62 | docs/_build/ 63 | 64 | # PyBuilder 65 | target/ 66 | 67 | #Ipython Notebook 68 | .ipynb_checkpoints 69 | 70 | #Demo file 71 | demo.py 72 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | # ===== Linux ====== 3 | dist: xenial 4 | python: 5 | - "3.4" 6 | - "3.5" 7 | - "3.6" 8 | - "3.7" 9 | - "3.8" 10 | - "3.8-dev" 11 | install: "pip install -r requirements/requirements.txt " 12 | script: python -m unittest discover 13 | 14 | matrix: 15 | include: 16 | - name: "Python 3.6.5 on macOS 10.13" 17 | os: osx 18 | osx_image: xcode9.4 # Python 3.6.5 running on macOS 10.13 19 | language: shell # 'language: python' is an error on Travis CI macOS 20 | before_install: 21 | - python3 --version 22 | - pip3 install -U pip 23 | - pip3 install -U pytest 24 | - pip3 install codecov 25 | script: python3 -m pytest 26 | after_success: python 3 -m codecov 27 | 28 | - name: "Python 3.7.5 on macOS 10.14" 29 | os: osx 30 | osx_image: xcode10.2 # Python 3.7.5 running on macOS 10.14.3 31 | language: shell # 'language: python' is an error on Travis CI macOS 32 | before_install: 33 | - python3 --version 34 | - pip3 install -U pip 35 | - pip3 install -U pytest 36 | - pip3 install codecov 37 | script: python3 -m pytest 38 | after_success: python 3 -m codecov 39 | 40 | - name: "Python 3.8.0 on macOS 10.14" 41 | os: osx 42 | osx_image: xcode11.3 # Python 3.8.0 running on macOS 10.14.6 43 | language: shell # 'language: python' is an error on Travis CI macOS 44 | before_install: 45 | - python3 --version 46 | - pip3 install -U pip 47 | - pip3 install -U pytest 48 | - pip3 install codecov 49 | script: python3 -m pytest 50 | after_success: python 3 -m codecov 51 | 52 | 53 | # ====== WINDOWS ========= 54 | - name: "Python 3.5.4 on Windows" 55 | os: windows # Windows 10.0.17134 N/A Build 17134 56 | language: shell # 'language: python' is an error on Travis CI Windows 57 | before_install: 58 | - choco install python --version 3.5.4 59 | - python --version 60 | - python -m pip install --upgrade pip 61 | - pip3 install --upgrade pytest 62 | - pip3 install codecov 63 | env: PATH=/c/Python35:/c/Python35/Scripts:$PATH 64 | 65 | - name: "Python 3.6.8 on Windows" 66 | os: windows # Windows 10.0.17134 N/A Build 17134 67 | language: shell # 'language: python' is an error on Travis CI Windows 68 | before_install: 69 | - choco install python --version 3.6.8 70 | - python --version 71 | - python -m pip install --upgrade pip 72 | - pip3 install --upgrade pytest 73 | - pip3 install codecov 74 | env: PATH=/c/Python36:/c/Python36/Scripts:$PATH -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements/* 2 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | release: 2 | python setup.py sdist upload -r pypi 3 | 4 | register: 5 | python setup.py sdist register -r pypi 6 | 7 | # Test it via `pip install -i https://testpypi.python.org/pypi ` 8 | test-release: 9 | python setup.py sdist upload -r test 10 | 11 | test-register: 12 | python setup.py sdist register -r test 13 | 14 | .PHONY: register test-register release test-release 15 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ***** 2 | Preprocessor 3 | ***** 4 | 5 | .. image:: https://travis-ci.org/s/preprocessor.svg?branch=master 6 | :target: https://travis-ci.org/s/preprocessor 7 | 8 | .. image:: https://img.shields.io/pypi/dm/tweet-preprocessor.svg 9 | :target: https://pypi.python.org/pypi/tweet-preprocessor/ 10 | 11 | .. image:: https://badge.fury.io/py/tweet-preprocessor.svg 12 | :target: https://pypi.python.org/pypi/tweet-preprocessor/ 13 | 14 | .. image:: https://img.shields.io/github/license/s/preprocessor.svg 15 | :target: https://github.com/s/preprocessor/blob/master/LICENSE.md 16 | 17 | .. image:: https://img.shields.io/pypi/pyversions/tweet-preprocessor.svg 18 | :target: https://pypi.python.org/pypi/tweet-preprocessor/ 19 | 20 | 21 | Preprocessor is a preprocessing library for tweet data written in 22 | Python. When building Machine Learning systems based on tweet and text data, a 23 | preprocessing is required. This is required because of quality of the data as well as dimensionality reduction purposes. 24 | 25 | This library makes it easy to clean, parse or tokenize the tweets so you don't have to write the same helper functions over and over again ever time. 26 | 27 | Features 28 | ======== 29 | 30 | Currently supports cleaning, tokenizing and parsing: 31 | 32 | - URLs 33 | - Hashtags 34 | - Mentions 35 | - Reserved words (RT, FAV) 36 | - Emojis 37 | - Smileys 38 | - Numbers 39 | - ``JSON`` and ``.txt`` file support 40 | 41 | Preprocessor ``v0.6.0`` supports 42 | ``Python 3.4+ on Linux, macOS and Windows``. Tests run on 43 | following setups: 44 | 45 | :: 46 | 47 | Linux Xenial with Python 3.4.8, 3.5.6, 3.6.7, 3.7.1, 3.8.0, 3.8.3+ 48 | macOS with Python 3.7.5, 3.8.0 49 | Windows with Python 3.5.4, 3.6.8 50 | 51 | Usage 52 | ===== 53 | 54 | Basic cleaning: 55 | --------------- 56 | 57 | .. code:: python 58 | 59 | >>> import preprocessor as p 60 | >>> p.clean('Preprocessor is #awesome 👍 https://github.com/s/preprocessor') 61 | 'Preprocessor is' 62 | 63 | Tokenizing: 64 | ----------- 65 | 66 | .. code:: python 67 | 68 | >>> p.tokenize('Preprocessor is #awesome 👍 https://github.com/s/preprocessor') 69 | 'Preprocessor is $HASHTAG$ $EMOJI$ $URL$' 70 | 71 | Parsing: 72 | -------- 73 | 74 | .. code:: python 75 | 76 | >>> parsed_tweet = p.parse('Preprocessor is #awesome https://github.com/s/preprocessor') 77 | 78 | >>> parsed_tweet.urls 79 | [(25:58) => https://github.com/s/preprocessor] 80 | >>> parsed_tweet.urls[0].start_index 81 | 25 82 | >>> parsed_tweet.urls[0].match 83 | 'https://github.com/s/preprocessor' 84 | >>> parsed_tweet.urls[0].end_index 85 | 58 86 | 87 | Fully customizable: 88 | ------------------- 89 | 90 | .. code:: python 91 | 92 | >>> p.set_options(p.OPT.URL, p.OPT.EMOJI) 93 | >>> p.clean('Preprocessor is #awesome 👍 https://github.com/s/preprocessor') 94 | 'Preprocessor is #awesome' 95 | 96 | Preprocessor will go through all of the options by default unless you 97 | specify some options. 98 | 99 | Processing files: 100 | ----------------- 101 | 102 | Preprocessor currently supports processing ``.json`` and ``.txt`` 103 | formats. Please see below examples for the correct input format. 104 | 105 | Example JSON file 106 | ~~~~~~~~~~~~~~~~~ 107 | 108 | .. code:: json 109 | 110 | [ 111 | "Preprocessor now supports files. https://github.com/s/preprocessor", 112 | "#preprocessing is a cruical part of @ML projects.", 113 | "@RT @Twitter raw text data usually has lots of #residue. http://t.co/g00gl" 114 | ] 115 | 116 | Example Text file 117 | ~~~~~~~~~~~~~~~~~ 118 | 119 | :: 120 | 121 | Preprocessor now supports files. https://github.com/s/preprocessor 122 | #preprocessing is a cruical part of @ML projects. 123 | @RT @Twitter raw text data usually has lots of #residue. http://t.co/g00gl 124 | 125 | Preprocessing JSON file: 126 | ~~~~~~~~~~~~~~~~~~~~~~~~ 127 | 128 | .. code:: python 129 | 130 | # JSON example 131 | >>> input_file_name = "sample_json.json" 132 | >>> p.clean_file(input_file_name, options=[p.OPT.URL, p.OPT.MENTION]) 133 | Saved the cleaned tweets to:/tests/artifacts/24052020_013451892752_vkeCMTwBEMmX_clean_file_sample.json 134 | 135 | Preprocessing text file: 136 | ~~~~~~~~~~~~~~~~~~~~~~~~ 137 | 138 | .. code:: python 139 | 140 | # Text file example 141 | >>> input_file_name = "sample_txt.txt" 142 | >>> p.clean_file(input_file_name, options=[p.OPT.URL, p.OPT.MENTION]) 143 | Saved the cleaned tweets to:/tests/artifacts/24052020_013451908865_TE9DWX1BjFws_clean_file_sample.txt 144 | 145 | Available Options: 146 | ~~~~~~~~~~~~~~~~~~ 147 | 148 | +------------------+---------------------+ 149 | | Option Name | Option Short Code | 150 | +==================+=====================+ 151 | | URL | p.OPT.URL | 152 | +------------------+---------------------+ 153 | | Mention | p.OPT.MENTION | 154 | +------------------+---------------------+ 155 | | Hashtag | p.OPT.HASHTAG | 156 | +------------------+---------------------+ 157 | | Reserved Words | p.OPT.RESERVED | 158 | +------------------+---------------------+ 159 | | Emoji | p.OPT.EMOJI | 160 | +------------------+---------------------+ 161 | | Smiley | p.OPT.SMILEY | 162 | +------------------+---------------------+ 163 | | Number | p.OPT.NUMBER | 164 | +------------------+---------------------+ 165 | 166 | Installation 167 | ============ 168 | 169 | Using pip: 170 | 171 | .. code:: bash 172 | 173 | $ pip install tweet-preprocessor 174 | 175 | 176 | Using Anaconda: 177 | 178 | .. code:: bash 179 | 180 | $ conda install -c saidozcan tweet-preprocessor 181 | 182 | Using manual installation: 183 | 184 | .. code:: bash 185 | 186 | $ python setup.py build 187 | $ python setup.py install 188 | 189 | Contributing 190 | ============ 191 | 192 | Are you willing to contribute to preprocessor? That's great! Please 193 | follow below steps to contribute to this project: 194 | 195 | #. Create a bug report or a feature idea using the templates on Issues 196 | page. 197 | 198 | #. Fork the repository and make your changes. 199 | 200 | #. Open a PR and make sure your PR has tests and all the checks pass. 201 | 202 | #. And that's all! 203 | 204 | .. |image| image:: https://travis-ci.org/s/preprocessor.svg?branch=master 205 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = docsbuild 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/preprocessor.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/preprocessor.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/preprocessor" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/preprocessor" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # preprocessor documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jan 26 00:04:16 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.doctest', 34 | ] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['docstemplates'] 38 | 39 | # The suffix(es) of source filenames. 40 | # You can specify multiple suffix as a list of string: 41 | # source_suffix = ['.rst', '.md'] 42 | source_suffix = '.rst' 43 | 44 | # The encoding of source files. 45 | #source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = u'preprocessor' 52 | copyright = u'2016, Said Özcan' 53 | author = u'Said Özcan' 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 = u'0.1.2' 61 | # The full version, including alpha/beta/rc tags. 62 | release = u'0.1.2' 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 = 'en' 70 | 71 | # There are two options for replacing |today|: either, you set today to some 72 | # non-false value, then it is used: 73 | #today = '' 74 | # Else, today_fmt is used as the format for a strftime call. 75 | #today_fmt = '%B %d, %Y' 76 | 77 | # List of patterns, relative to source directory, that match files and 78 | # directories to ignore when looking for source files. 79 | exclude_patterns = ['docsbuild'] 80 | 81 | # The reST default role (used for this markup: `text`) to use for all 82 | # documents. 83 | #default_role = None 84 | 85 | # If true, '()' will be appended to :func: etc. cross-reference text. 86 | #add_function_parentheses = True 87 | 88 | # If true, the current module name will be prepended to all description 89 | # unit titles (such as .. function::). 90 | #add_module_names = True 91 | 92 | # If true, sectionauthor and moduleauthor directives will be shown in the 93 | # output. They are ignored by default. 94 | #show_authors = False 95 | 96 | # The name of the Pygments (syntax highlighting) style to use. 97 | pygments_style = 'sphinx' 98 | 99 | # A list of ignored prefixes for module index sorting. 100 | #modindex_common_prefix = [] 101 | 102 | # If true, keep warnings as "system message" paragraphs in the built documents. 103 | #keep_warnings = False 104 | 105 | # If true, `todo` and `todoList` produce output, else they produce nothing. 106 | todo_include_todos = False 107 | 108 | 109 | # -- Options for HTML output ---------------------------------------------- 110 | 111 | # The theme to use for HTML and HTML Help pages. See the documentation for 112 | # a list of builtin themes. 113 | html_theme = 'sphinx_rtd_theme' 114 | 115 | # Theme options are theme-specific and customize the look and feel of a theme 116 | # further. For a list of options available for each theme, see the 117 | # documentation. 118 | #html_theme_options = {} 119 | 120 | # Add any paths that contain custom themes here, relative to this directory. 121 | #html_theme_path = [] 122 | 123 | # The name for this set of Sphinx documents. If None, it defaults to 124 | # " v documentation". 125 | #html_title = None 126 | 127 | # A shorter title for the navigation bar. Default is the same as html_title. 128 | #html_short_title = None 129 | 130 | # The name of an image file (relative to this directory) to place at the top 131 | # of the sidebar. 132 | #html_logo = None 133 | 134 | # The name of an image file (within the static path) to use as favicon of the 135 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 136 | # pixels large. 137 | #html_favicon = None 138 | 139 | # Add any paths that contain custom static files (such as style sheets) here, 140 | # relative to this directory. They are copied after the builtin static files, 141 | # so a file named "default.css" will overwrite the builtin "default.css". 142 | html_static_path = ['docsstatic'] 143 | 144 | # Add any extra paths that contain custom files (such as robots.txt or 145 | # .htaccess) here, relative to this directory. These files are copied 146 | # directly to the root of the documentation. 147 | #html_extra_path = [] 148 | 149 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 150 | # using the given strftime format. 151 | #html_last_updated_fmt = '%b %d, %Y' 152 | 153 | # If true, SmartyPants will be used to convert quotes and dashes to 154 | # typographically correct entities. 155 | #html_use_smartypants = True 156 | 157 | # Custom sidebar templates, maps document names to template names. 158 | #html_sidebars = {} 159 | 160 | # Additional templates that should be rendered to pages, maps page names to 161 | # template names. 162 | #html_additional_pages = {} 163 | 164 | # If false, no module index is generated. 165 | #html_domain_indices = True 166 | 167 | # If false, no index is generated. 168 | #html_use_index = True 169 | 170 | # If true, the index is split into individual pages for each letter. 171 | #html_split_index = False 172 | 173 | # If true, links to the reST sources are added to the pages. 174 | #html_show_sourcelink = True 175 | 176 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 177 | #html_show_sphinx = True 178 | 179 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages will 183 | # contain a tag referring to it. The value of this option must be the 184 | # base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Language to be used for generating the HTML full-text search index. 191 | # Sphinx supports the following languages: 192 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 193 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 194 | #html_search_language = 'en' 195 | 196 | # A dictionary with options for the search language support, empty by default. 197 | # Now only 'ja' uses this config value 198 | #html_search_options = {'type': 'default'} 199 | 200 | # The name of a javascript file (relative to the configuration directory) that 201 | # implements a search results scorer. If empty, the default will be used. 202 | #html_search_scorer = 'scorer.js' 203 | 204 | # Output file base name for HTML help builder. 205 | htmlhelp_basename = 'preprocessordoc' 206 | 207 | # -- Options for LaTeX output --------------------------------------------- 208 | 209 | latex_elements = { 210 | # The paper size ('letterpaper' or 'a4paper'). 211 | #'papersize': 'letterpaper', 212 | 213 | # The font size ('10pt', '11pt' or '12pt'). 214 | #'pointsize': '10pt', 215 | 216 | # Additional stuff for the LaTeX preamble. 217 | #'preamble': '', 218 | 219 | # Latex figure (float) alignment 220 | #'figure_align': 'htbp', 221 | } 222 | 223 | # Grouping the document tree into LaTeX files. List of tuples 224 | # (source start file, target name, title, 225 | # author, documentclass [howto, manual, or own class]). 226 | latex_documents = [ 227 | (master_doc, 'preprocessor.tex', u'preprocessor Documentation', 228 | u'Said Özcan', 'manual'), 229 | ] 230 | 231 | # The name of an image file (relative to this directory) to place at the top of 232 | # the title page. 233 | #latex_logo = None 234 | 235 | # For "manual" documents, if this is true, then toplevel headings are parts, 236 | # not chapters. 237 | #latex_use_parts = False 238 | 239 | # If true, show page references after internal links. 240 | #latex_show_pagerefs = False 241 | 242 | # If true, show URL addresses after external links. 243 | #latex_show_urls = False 244 | 245 | # Documents to append as an appendix to all manuals. 246 | #latex_appendices = [] 247 | 248 | # If false, no module index is generated. 249 | #latex_domain_indices = True 250 | 251 | 252 | # -- Options for manual page output --------------------------------------- 253 | 254 | # One entry per manual page. List of tuples 255 | # (source start file, name, description, authors, manual section). 256 | man_pages = [ 257 | (master_doc, 'preprocessor', u'preprocessor Documentation', 258 | [author], 1) 259 | ] 260 | 261 | # If true, show URL addresses after external links. 262 | #man_show_urls = False 263 | 264 | 265 | # -- Options for Texinfo output ------------------------------------------- 266 | 267 | # Grouping the document tree into Texinfo files. List of tuples 268 | # (source start file, target name, title, author, 269 | # dir menu entry, description, category) 270 | texinfo_documents = [ 271 | (master_doc, 'preprocessor', u'preprocessor Documentation', 272 | author, 'preprocessor', 'One line description of project.', 273 | 'Miscellaneous'), 274 | ] 275 | 276 | # Documents to append as an appendix to all manuals. 277 | #texinfo_appendices = [] 278 | 279 | # If false, no module index is generated. 280 | #texinfo_domain_indices = True 281 | 282 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 283 | #texinfo_show_urls = 'footnote' 284 | 285 | # If true, do not generate a @detailmenu in the "Top" node's menu. 286 | #texinfo_no_detailmenu = False 287 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. preprocessor documentation master file, created by 2 | sphinx-quickstart on Tue Jan 26 00:04:16 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Preprocessor 7 | ======================================== 8 | 9 | Preprocessor's goal is to make preprocessing tweet data easy. It gets you what you need with a clean syntax. 10 | 11 | >>> import preprocessor 12 | >>> cleaned_tweet = preprocessor.clean("Preprocessor is #awesome https://github.com/s/preprocessor") 13 | Preprocessor is 14 | 15 | .. toctree:: 16 | :maxdepth: 2 17 | -------------------------------------------------------------------------------- /preprocessor/__init__.py: -------------------------------------------------------------------------------- 1 | from .api import clean, tokenize, parse, set_options, clean_file 2 | from .defines import Options as OPT 3 | from .defines import InputFileType, Defines 4 | from .utils import get_worker_methods,\ 5 | get_file_contents,\ 6 | get_json_file_contents,\ 7 | get_text_file_contents,\ 8 | get_file_extension,\ 9 | write_to_output_file,\ 10 | write_to_json_file,\ 11 | write_to_text_file,\ 12 | generate_random_file_name,\ 13 | generate_random_alphanumeric_string, \ 14 | are_lists_equal 15 | 16 | __all__ = [clean, 17 | tokenize, 18 | parse, 19 | set_options, 20 | InputFileType, 21 | get_worker_methods, 22 | get_file_contents, 23 | get_json_file_contents, 24 | get_text_file_contents, 25 | get_file_extension, 26 | write_to_output_file, 27 | write_to_json_file, 28 | write_to_text_file, 29 | generate_random_file_name, 30 | generate_random_alphanumeric_string, 31 | are_lists_equal] -------------------------------------------------------------------------------- /preprocessor/api.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | preprocessor.api 4 | ~~~~~~~~~~~~ 5 | This module implements the Preprocessor API. 6 | 7 | :copyright: (c) 2016 by Said Özcan. 8 | :license: GPLv3, see LICENSE for more details. 9 | 10 | """ 11 | 12 | from .preprocess import Preprocess 13 | from .defines import Functions, Defines 14 | from .parse import Parse 15 | from .utils import * 16 | 17 | preprocessor = Preprocess() 18 | parser = Parse() 19 | 20 | def clean(tweet_string): 21 | """Cleans irrelevant information from a tweet text`. 22 | :param tweet_string: A tweet text to clean. 23 | :return: Cleaned tweet text. 24 | :rtype: string 25 | Usage:: 26 | >>> import preprocessor 27 | >>> cleaned_tweet = preprocessor.clean("Preprocessor is #awesome https://github.com/s/preprocessor") 28 | Preprocessor is 29 | """ 30 | cleaned_tweet_string = preprocessor.clean(tweet_string, Functions.CLEAN) 31 | return cleaned_tweet_string 32 | 33 | def tokenize(tweet_string): 34 | """Tokenizes irrelevant information in a tweet text`. 35 | :param tweet_string: A tweet text to tokenize. 36 | :return: Tokenized tweet text. 37 | :rtype: string 38 | Usage:: 39 | >>> import preprocessor 40 | >>> tokenized_tweet = preprocessor.tokenize("Preprocessor is #awesome https://github.com/s/preprocessor") 41 | Preprocessor is $HASHTAG$ $URL$ 42 | """ 43 | tokenized_tweet_string = preprocessor.clean(tweet_string, Functions.TOKENIZE) 44 | return tokenized_tweet_string 45 | 46 | def parse(tweet_string): 47 | """Parses given a tweet text and returns an object`. 48 | :param tweet_string: A tweet text to parse. 49 | :return: Parsed tweet. 50 | :rtype: preprocessor.parse.ParseResult 51 | Usage:: 52 | >>> import preprocessor 53 | >>> parsed_tweet = preprocessor.parse("Preprocessor is #awesome https://github.com/s/preprocessor") 54 | preprocessor.parse.ParseResult 55 | >>> parsed_tweet.urls 56 | [(25:58) => https://github.com/s/preprocessor] 57 | >>> parsed_tweet.urls[0].start_index 58 | 25 59 | """ 60 | parsed_tweet_obj = parser.parse(tweet_string) 61 | return parsed_tweet_obj 62 | 63 | def set_options(*args): 64 | """Sets desired options for preprocessing`. 65 | :param *args: A number of preprocessor.OPT options 66 | :return: void 67 | :rtype: void 68 | Usage:: 69 | >>> import preprocessor 70 | >>> preprocessor.set_options(preprocessor.OPT.URL, preprocessor.OPT.SMILEY) 71 | """ 72 | Defines.FILTERED_METHODS = list(args) 73 | 74 | 75 | def clean_file(input_file_path, add_timestamp=False, *options): 76 | """Cleans given input file in JSON and txt format if it can be found at the given path. 77 | Returns a stdout for the output file path. 78 | :param input_file_path: Absolute path for the tweets. Could be either in JSON or .txt format. 79 | :param add_timestamp: If True, adds current timestamp to the filename 80 | :return: output file path: str. Returns the file path of the cleaned file. 81 | :rtype: str 82 | :raises IOError if the input file empty 83 | Usage:: 84 | >>> input_file_name = "sample.json" 85 | >>> p.clean_file(file_name, p.OPT.URL, p.OPT.MENTION) 86 | """ 87 | file_contents = get_file_contents(input_file_path) 88 | if not file_contents or len(file_contents) == 0: 89 | raise IOError("Empty file given at path:" + input_file_path) 90 | 91 | cleaned_content = [] 92 | for line in file_contents: 93 | cleaned_content.append(clean(line)) 94 | output_path = write_to_output_file(input_file_path, cleaned_content, add_timestamp) 95 | print("Saved the cleaned tweets to:" + output_path) 96 | return output_path 97 | -------------------------------------------------------------------------------- /preprocessor/defines.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | preprocessor.constants 4 | ~~~~~~~~~~~~ 5 | This module includes the constant variables used in Preprocessor 6 | """ 7 | import re 8 | from .enum import enum 9 | 10 | opts = { 11 | 'URL': 'urls', 12 | 'MENTION': 'mentions', 13 | 'HASHTAG': 'hashtags', 14 | 'RESERVED': 'reserved_words', 15 | 'EMOJI': 'emojis', 16 | 'SMILEY': 'smileys', 17 | 'NUMBER': 'numbers', 18 | 'ESCAPE_CHAR': 'escape_chars' 19 | } 20 | Options = enum(**opts) 21 | Functions = enum('CLEAN', 'TOKENIZE', 'PARSE') 22 | 23 | input_file_type = { 24 | 'json': '.json', 25 | 'text': '.txt', 26 | 'unsupported': 'unsupported' 27 | } 28 | InputFileType = enum(**input_file_type) 29 | 30 | 31 | class Defines: 32 | PARSE_METHODS_PREFIX = 'parse_' 33 | FILTERED_METHODS = opts.values() 34 | PREPROCESS_METHODS_PREFIX = 'preprocess_' 35 | PRIORITISED_METHODS = ['urls', 'mentions', 'hashtags', 'emojis', 'smileys'] 36 | 37 | 38 | class Patterns: 39 | URL_PATTERN_STR = r"""(?i)((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info 40 | |int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba| 41 | bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy| 42 | cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr| 43 | gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz| 44 | la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne| 45 | nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg| 46 | sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug| 47 | uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()] 48 | *?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’])|(?:(? %s' % (self.start_index, self.end_index, self.match) 33 | 34 | 35 | class Parse: 36 | 37 | def __init__(self): 38 | pass 39 | 40 | def parse(self, tweet_string): 41 | parse_result_obj = ParseResult() 42 | 43 | parser_methods = get_worker_methods(self, Defines.PARSE_METHODS_PREFIX) 44 | 45 | for a_parser_method in parser_methods: 46 | method_to_call = getattr(self, a_parser_method) 47 | attr = a_parser_method.split('_')[1] 48 | 49 | items = method_to_call(tweet_string) 50 | setattr(parse_result_obj, attr, items) 51 | 52 | return parse_result_obj 53 | 54 | def parser(self, pattern, string): 55 | 56 | match_items = [] 57 | number_match_max_group_count = 2 58 | 59 | for match_object in re.finditer(pattern, string): 60 | start_index = match_object.start() 61 | end_index = match_object.end() 62 | 63 | if Patterns.NUMBERS_PATTERN == pattern and number_match_max_group_count == len(match_object.groups()): 64 | match_str = match_object.groups()[1] 65 | else: 66 | match_str = match_object.group() 67 | 68 | parse_item = ParseItem(start_index, end_index, match_str) 69 | match_items.append(parse_item) 70 | 71 | if len(match_items): 72 | return match_items 73 | 74 | def parse_urls(self, tweet_string): 75 | return self.parser(Patterns.URL_PATTERN, tweet_string) 76 | 77 | def parse_hashtags(self, tweet_string): 78 | return self.parser(Patterns.HASHTAG_PATTERN, tweet_string) 79 | 80 | def parse_mentions(self, tweet_string): 81 | return self.parser(Patterns.MENTION_PATTERN, tweet_string) 82 | 83 | def parse_reserved_words(self, tweet_string): 84 | return self.parser(Patterns.RESERVED_WORDS_PATTERN, tweet_string) 85 | 86 | def parse_emojis(self, tweet_string): 87 | return self.parser(Patterns.EMOJIS_PATTERN, tweet_string) 88 | 89 | def parse_smileys(self, tweet_string): 90 | return self.parser(Patterns.SMILEYS_PATTERN, tweet_string) 91 | 92 | def parse_numbers(self, tweet_string): 93 | return self.parser(Patterns.NUMBERS_PATTERN, tweet_string) -------------------------------------------------------------------------------- /preprocessor/preprocess.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | preprocessor.preprocess 5 | ~~~~~~~~~~~~ 6 | This module includes preprocess functionality 7 | 8 | """ 9 | 10 | from .defines import * 11 | from .utils import get_worker_methods 12 | 13 | 14 | class Preprocess: 15 | 16 | tweet = None 17 | 18 | def __init__(self): 19 | self.repl = None 20 | 21 | def clean(self, tweet_string, repl): 22 | 23 | cleaner_methods = get_worker_methods(self, Defines.PREPROCESS_METHODS_PREFIX) 24 | for a_cleaner_method in cleaner_methods: 25 | token = self.get_token_string_from_method_name(a_cleaner_method) 26 | method_to_call = getattr(self, a_cleaner_method) 27 | 28 | if repl == Functions.CLEAN: 29 | tweet_string = method_to_call(tweet_string, '') 30 | else: 31 | tweet_string = method_to_call(tweet_string, token) 32 | 33 | tweet_string = self.remove_unneccessary_characters(tweet_string) 34 | return tweet_string 35 | 36 | def preprocess_urls(self, tweet_string, repl): 37 | return Patterns.URL_PATTERN.sub(repl, tweet_string) 38 | 39 | def preprocess_hashtags(self, tweet_string, repl): 40 | return Patterns.HASHTAG_PATTERN.sub(repl, tweet_string) 41 | 42 | def preprocess_mentions(self, tweet_string, repl): 43 | return Patterns.MENTION_PATTERN.sub(repl, tweet_string) 44 | 45 | def preprocess_reserved_words(self, tweet_string, repl): 46 | return Patterns.RESERVED_WORDS_PATTERN.sub(repl, tweet_string) 47 | 48 | def preprocess_emojis(self, tweet_string, repl): 49 | processed = Patterns.EMOJIS_PATTERN.sub(repl, tweet_string) 50 | return processed.encode('ascii', 'ignore').decode('ascii') 51 | 52 | def preprocess_smileys(self, tweet_string, repl): 53 | return Patterns.SMILEYS_PATTERN.sub(repl, tweet_string) 54 | 55 | def preprocess_numbers(self, tweet_string, repl): 56 | return re.sub(Patterns.NUMBERS_PATTERN, lambda m: m.groups()[0] + repl, tweet_string) 57 | 58 | def preprocess_escape_chars(self, tweet_string, repl): 59 | """ 60 | This method processes escape chars using ASCII control characters. 61 | :param tweet_string: input string which will be used to remove escape chars 62 | :param repl: unused for this method 63 | :return: processed string 64 | """ 65 | escapes = ''.join([chr(char) for char in range(1, 32)]) 66 | translator = str.maketrans('', '', escapes) 67 | return tweet_string.translate(translator) 68 | 69 | def remove_unneccessary_characters(self, tweet_string): 70 | return ' '.join(tweet_string.split()) 71 | 72 | def get_token_string_from_method_name(self, method_name): 73 | token_string = method_name.rstrip('s') 74 | token_string = token_string.split('_')[1] 75 | token_string = token_string.upper() 76 | token_string = '$' + token_string + '$' 77 | return token_string -------------------------------------------------------------------------------- /preprocessor/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | preprocessor.utils 4 | ~~~~~~~~~~~~~~ 5 | This module includes utility methods which are used in Preprocessor 6 | """ 7 | 8 | import json 9 | import random 10 | import string 11 | from os import path 12 | from datetime import datetime 13 | from .defines import Defines, InputFileType 14 | 15 | 16 | def get_worker_methods(obj, prefix): 17 | all_methods = dir(obj) 18 | relevant_methods = list(filter(lambda x: x.startswith(prefix), all_methods)) 19 | 20 | # Filtering according to user's options 21 | prefixed_filtered_methods = [prefix + fm for fm in Defines.FILTERED_METHODS] 22 | filtered_methods = list(filter(lambda x: x in prefixed_filtered_methods, relevant_methods)) 23 | 24 | # Prioritising 25 | offset = 0 26 | for ind, pri_method in enumerate(Defines.PRIORITISED_METHODS): 27 | prefixed_pri_method = prefix + pri_method 28 | if pri_method in filtered_methods: 29 | filtered_methods.remove(prefixed_pri_method) 30 | filtered_methods.insert(offset + ind, prefixed_pri_method) 31 | 32 | return filtered_methods 33 | 34 | 35 | def get_file_contents(file_path): 36 | """ 37 | Returns the type of the file in InputFileType enum type 38 | if the file exists at given path. 39 | :param file_path: Absolute path for the file. 40 | :return: file_type (json, text, unsupported) 41 | :rtype: InputFileType or None 42 | :raises: This method raises OSError if it cannot read file_path. 43 | """ 44 | if not path.exists(file_path): 45 | return None 46 | file_ext = get_file_extension(file_path) 47 | if InputFileType.json == file_ext: 48 | return get_json_file_contents(file_path) 49 | else: 50 | return get_text_file_contents(file_path) 51 | 52 | 53 | def get_json_file_contents(file_path): 54 | """ 55 | Returns contents of a JSON file as a string array. 56 | :param file_path: Absolute path for the file. 57 | :return: str array or None 58 | :rtype: List 59 | :raises: This method raises OSError if it cannot read file_path. 60 | """ 61 | with open(file_path, encoding='utf-8') as handler: 62 | return json.load(handler) 63 | 64 | 65 | def get_text_file_contents(file_path): 66 | """ 67 | Returns contents of a JSON file as a string array. 68 | :param file_path: Absolute path for the file. 69 | :return: str array or None 70 | :rtype: List 71 | :raises: This method raises OSError if it cannot read file_path. 72 | """ 73 | with open(file_path, encoding='utf-8') as handler: 74 | content = handler.readlines() 75 | return [line.rstrip("\n") for line in content] 76 | 77 | 78 | def get_file_extension(file_path): 79 | """ 80 | Returns extension for a given file path. 81 | :param file_path: Absolute path for the file. 82 | :return: file extension 83 | :rtype: str 84 | """ 85 | components = list(filter(None, path.splitext(file_path))) 86 | if len(components) == 1 and not components[0].startswith("."): 87 | return None 88 | 89 | return components[-1] if len(components) > 0 else None 90 | 91 | 92 | def write_to_output_file(file_path, file_contents, add_timestamp=False): 93 | """ 94 | Writes the given file_contents to the file_path directory in given file format 95 | if current user's permissions grants to do so. 96 | :param file_path: str: Absolute path for the file 97 | :param file_contents: List: Contents of the file 98 | :param add_timestamp: If True, adds current timestamp to the filename 99 | :return: Output path 100 | :rtype: str 101 | :raises: ValueError if file_format is neither json nor text. 102 | """ 103 | file_format = get_file_extension(file_path) 104 | if not file_format: 105 | raise ValueError('Given file path:'+file_path+' does not have a file name and extension.') 106 | 107 | output_file_path = generate_random_file_name(file_path, add_timestamp) 108 | if InputFileType.json == file_format: 109 | return write_to_json_file(output_file_path, file_contents) 110 | elif InputFileType.text == file_format: 111 | return write_to_text_file(output_file_path, file_contents) 112 | else: 113 | raise ValueError('Unrecognized file format. ' 114 | 'Cannot write to file path:'+file_path+' in '+file_format+' format.') 115 | 116 | 117 | def write_to_json_file(file_path, file_contents): 118 | """ 119 | Writes the given file_contents to the file_path in JSON format if current 120 | user's permissions grants to do so. 121 | :param file_path: Absolute path for the file 122 | :param file_contents: Contents of the output file 123 | :return: Output path 124 | :rtype: str 125 | :raises: This method raises OSError if it cannot write to file_path. 126 | """ 127 | with open(file_path, mode='w', encoding='utf-8') as handler: 128 | json.dump(file_contents, handler) 129 | return file_path 130 | 131 | 132 | def write_to_text_file(file_path, file_contents): 133 | """ 134 | Writes the given file_contents to the file_path in text format 135 | if current user's permissions grants to do so. 136 | :param file_path: Absolute path for the file 137 | :param file_contents: List List of lines 138 | :return: void 139 | :rtype: void 140 | :raises: This method raises OSError if it cannot write to file_path. 141 | """ 142 | with open(file_path, mode='w', encoding='utf-8') as handler: 143 | for line in file_contents: 144 | handler.write("%s\n" % line) 145 | return file_path 146 | 147 | 148 | def generate_random_file_name(file_path, add_timestamp=False): 149 | """ 150 | Generates a random file name for the given absolute file path. 151 | :param file_path: Absolute path for the file 152 | :param add_timestamp: If True, adds current timestamp to the filename 153 | :return: Absolute path for the file with a random file name 154 | :rtype: str 155 | """ 156 | file_path_components = list(path.split(file_path)) 157 | if len(file_path_components) == 0 or len(file_path) == 0: 158 | raise ValueError('Found faulty file path: ' + file_path + ' while trying to write to JSON file.') 159 | 160 | random_file_name = generate_random_alphanumeric_string() 161 | if add_timestamp: 162 | timestamp_str = get_current_timestamp("%d%m%Y_%H%M%S%f") 163 | random_file_name = timestamp_str + "_" + random_file_name 164 | 165 | file_name = random_file_name + "_" + file_path_components[-1] 166 | file_path_components[-1] = file_name 167 | return path.join(*file_path_components) 168 | 169 | 170 | def generate_random_alphanumeric_string(str_length=12): 171 | """ 172 | Generates a random string of length: str_length 173 | :param str_length: Character count of the output string 174 | :return: Randomly generated string 175 | :rtype: str 176 | """ 177 | letters_and_digits = string.ascii_letters + string.digits 178 | return ''.join((random.choice(letters_and_digits) for i in range(str_length))) 179 | 180 | 181 | def are_lists_equal(lhs_list, rhs_list): 182 | """ 183 | Compares two lists element by element and returns True if all of them are equal. 184 | :param lhs_list: First list to compare 185 | :param rhs_list: Second list to compare 186 | :return: True if lists are equal. False otherwise. 187 | :rtype: bool 188 | """ 189 | if not isinstance(lhs_list, list) or not isinstance(rhs_list, list): 190 | raise ValueError("One of the parameters isn't type of list.") 191 | lhs = [] 192 | rhs = [] 193 | 194 | if len(lhs_list) < len(rhs_list): 195 | lhs = rhs_list 196 | rhs = lhs_list 197 | return len((list(set(lhs) - set(rhs)))) == 0 198 | 199 | 200 | def get_current_timestamp(format_specifier): 201 | """ 202 | Returns current date and time in specified format 203 | :param format_specifier: format specifier for the date time object 204 | :return: Formatted date time string 205 | :rtype: str 206 | """ 207 | date_time = datetime.now() 208 | return date_time.strftime(format_specifier) 209 | -------------------------------------------------------------------------------- /requirements/dev-requirements.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | 3 | Sphinx 4 | -------------------------------------------------------------------------------- /requirements/requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/s/preprocessor/efd2eb5919187a1a6713f8bb3fb19861d6133392/requirements/requirements.txt -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from setuptools import setup, find_packages 3 | 4 | with open('README.rst', encoding='utf-8', errors='ignore') as f: 5 | long_description = f.read() 6 | 7 | 8 | setup( 9 | name='tweet-preprocessor', 10 | version='0.6.0', 11 | description='Elegant tweet preprocessing', 12 | long_description=long_description, 13 | author='Said Özcan', 14 | author_email='', 15 | url='https://github.com/s/preprocessor', 16 | packages=find_packages(), 17 | classifiers=[ 18 | 'Development Status :: 3 - Alpha', 19 | 'Environment :: Console', 20 | 'Environment :: Web Environment', 21 | 'Intended Audience :: Developers', 22 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 23 | 'Operating System :: MacOS :: MacOS X', 24 | 'Operating System :: Microsoft :: Windows', 25 | 'Operating System :: POSIX :: Linux', 26 | 'Programming Language :: Python :: 3.4', 27 | 'Programming Language :: Python :: 3.5', 28 | 'Programming Language :: Python :: 3.5', 29 | 'Programming Language :: Python :: 3.6', 30 | 'Programming Language :: Python :: 3.6', 31 | 'Programming Language :: Python :: 3.7', 32 | 'Programming Language :: Python :: 3.8', 33 | 'Programming Language :: Python :: 3.8', 34 | 'Programming Language :: Python :: Implementation :: PyPy', 35 | ], 36 | keywords='machine learning, preprocessing, processing, tweet, tokenizing, dimensionality reduction', 37 | ) 38 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | 5 | -------------------------------------------------------------------------------- /tests/artifacts/clean_file_sample.json: -------------------------------------------------------------------------------- 1 | [ 2 | "Preprocessor now supports files. https://github.com/s/preprocessor", 3 | "#preprocessing is a cruical part of @ML projects.", 4 | "@RT @Twitter raw text data usually has lots of #residue. http://t.co/g00gl", 5 | "#emoji #smiley 😀😍 https://emojipedia.org" 6 | ] -------------------------------------------------------------------------------- /tests/artifacts/clean_file_sample.txt: -------------------------------------------------------------------------------- 1 | Preprocessor now supports files. https://github.com/s/preprocessor 2 | #preprocessing is a cruical part of @ML projects. 3 | @RT @Twitter raw text data usually has lots of #residue. http://t.co/g00gl 4 | #emoji #smiley 😀😍 https://emojipedia.org 5 | -------------------------------------------------------------------------------- /tests/test_api.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import unittest 5 | import preprocessor as p 6 | 7 | 8 | class PreprocessorTest(unittest.TestCase): 9 | _artifacts_dir_name = "artifacts" 10 | 11 | def test_clean(self): 12 | tweet = "Hello there! @pyistanbul #packathon was awesome exp 😀. http://packathon.org" 13 | p.set_options(p.OPT.URL, p.OPT.HASHTAG, p.OPT.MENTION, p.OPT.EMOJI, p.OPT.SMILEY) 14 | cleaned_tweet = p.clean(tweet) 15 | self.assertEqual(cleaned_tweet, 'Hello there! was awesome exp .') 16 | 17 | def test_clean_urls(self): 18 | tweet = 'canbe foundathttp://www.osp.gatech.edu/rates/(http://www.osp.gatech.edu/rates/).' 19 | p.set_options(p.OPT.URL) 20 | cleaned_tweet = p.clean(tweet) 21 | self.assertEqual("canbe foundat.", cleaned_tweet) 22 | 23 | tweet = 'Nature:先日フランスで起きた臨床試験事故https://t.co/aHk5ok9CDg 原因究明まだなので早急な印象がするけど、低用量投与を1回' \ 24 | 'やった後で、(別のボランティアに)高用量の投与とかしてる試験方式にも問題があるだろうみたいなことを書いてる' 25 | cleaned_tweet = p.clean(tweet) 26 | self.assertEqual('Nature:先日フランスで起きた臨床試験事故 原因究明まだなので早急な印象がするけど、' 27 | '低用量投与を1回やった後で、(別のボランティアに)高用量の投与とかしてる試験方式にも問題があるだろうみたいなことを書いてる', 28 | cleaned_tweet) 29 | 30 | tweet = '[https://link.springer.com/article/10.1007/s10940\\-016\\-9314\\-9]' 31 | cleaned_tweet = p.clean(tweet) 32 | self.assertEqual('[]', cleaned_tweet) 33 | 34 | tweet = '(https://link.springer.com/article/10.1007/s10940-016-9314-9)' 35 | cleaned_tweet = p.clean(tweet) 36 | self.assertEqual('()', cleaned_tweet) 37 | 38 | tweet = 'check this link: https://fa.wikipedia.org/wiki/%D8%AD%D9%85%D9%84%D9%87_%D8%A8%D9%87_%DA%A9%D9%88%DB%8C' \ 39 | '_%D8%AF%D8%A7%D9%86%D8%B4%DA%AF%D8%A7%D9%87_%D8%AA%D9%87%D8%B1%D8%A7%D9%86_(%DB%B1%DB%B8%E2%80%93%DB%B2%' \ 40 | 'DB%B3_%D8%AA%DB%8C%D8%B1_%DB%B1%DB%B3%DB%B7%DB%B8) …' 41 | cleaned_tweet = p.clean(tweet) 42 | self.assertEqual('check this link: …', cleaned_tweet) 43 | 44 | def test_clean_smileys(self): 45 | tweet = "😀 :) expression experience zoxo xoyo 💁‍♂️🙍‍♀️🙍‍♀️🧢🐄🧑‍🤝‍🧑" 46 | p.set_options(p.OPT.SMILEY, p.OPT.EMOJI) 47 | cleaned_tweet = p.clean(tweet) 48 | self.assertEqual('expression experience zoxo xoyo', cleaned_tweet) 49 | 50 | def test_clean_reserved_words(self): 51 | tweet = "Awesome!!! RT @RT: This is a tweet about art ART. FAV #RT #FAV #hashtag" 52 | p.set_options(p.OPT.RESERVED) 53 | cleaned_tweet = p.clean(tweet) 54 | self.assertEqual('Awesome!!! @RT: This is a tweet about art ART. #RT #FAV #hashtag', cleaned_tweet) 55 | 56 | def test_tokenize(self): 57 | tweet = 'Packathon was a really #nice :) challenging 👌. @packathonorg http://packathon.org' 58 | p.set_options(p.OPT.URL, p.OPT.HASHTAG, p.OPT.MENTION, p.OPT.EMOJI, p.OPT.SMILEY) 59 | tokenized_tweet = p.tokenize(tweet) 60 | self.assertEqual(tokenized_tweet, 'Packathon was a really $HASHTAG$ $SMILEY$ challenging $EMOJI$. $MENTION$ $URL$') 61 | 62 | def test_parse(self): 63 | tweet = 'A tweet with #hashtag :) @mention 😀 and http://github.com/s.' 64 | p.set_options(p.OPT.URL, p.OPT.HASHTAG, p.OPT.MENTION, p.OPT.EMOJI, p.OPT.SMILEY) 65 | parsed_tweet = p.parse(tweet) 66 | 67 | self.assertIsNotNone(parsed_tweet.urls) 68 | self.assertEqual(1, len(parsed_tweet.urls)) 69 | 70 | self.assertIsNotNone(parsed_tweet.hashtags) 71 | self.assertEqual(1, len(parsed_tweet.hashtags)) 72 | 73 | self.assertIsNotNone(parsed_tweet.mentions) 74 | self.assertEqual(1, len(parsed_tweet.mentions)) 75 | 76 | self.assertIsNone(parsed_tweet.reserved_words) 77 | 78 | self.assertIsNotNone(parsed_tweet.emojis) 79 | self.assertEqual(1, len(parsed_tweet.emojis)) 80 | self.assertEqual("😀", parsed_tweet.emojis[0].match) 81 | 82 | self.assertIsNotNone(parsed_tweet.smileys) 83 | self.assertEqual(1, len(parsed_tweet.smileys)) 84 | self.assertEqual(":)", parsed_tweet.smileys[0].match) 85 | 86 | def test_set_options(self): 87 | tweet = 'Preprocessor now has custom #options support! https://github.com/s/preprocessor' 88 | p.set_options(p.OPT.URL) 89 | parsed_tweet = p.parse(tweet) 90 | 91 | self.assertIsNone(parsed_tweet.hashtags) 92 | self.assertIsNotNone(parsed_tweet.urls) 93 | 94 | def test_clean_file(self): 95 | current_dir = os.path.dirname(__file__) 96 | artifacts_dir = os.path.join(current_dir, self._artifacts_dir_name) 97 | extensions = [p.InputFileType.json, p.InputFileType.text] 98 | for ext in extensions: 99 | full_input_path = os.path.join(artifacts_dir, "clean_file_sample" + ext) 100 | raw_data = p.get_file_contents(full_input_path) 101 | self.assertIsNotNone(raw_data) 102 | 103 | # Test all option 104 | check_against = self._get_test_data_for_option(raw_data) 105 | self._test_clean_file(full_input_path, check_against) 106 | 107 | # Test individual options 108 | options = [ 109 | p.OPT.URL, 110 | p.OPT.MENTION, 111 | p.OPT.HASHTAG, 112 | p.OPT.RESERVED, 113 | p.OPT.EMOJI, 114 | p.OPT.SMILEY, 115 | p.OPT.NUMBER 116 | ] 117 | for opt in options: 118 | check_against = self._get_test_data_for_option(raw_data, opt) 119 | self._test_clean_file(full_input_path, check_against, opt) 120 | 121 | def test_escape_chars(self): 122 | p.set_options(p.OPT.ESCAPE_CHAR) 123 | input_str = u"\x01\x02\x03\x04I \x05\x06\x07\x10\x11have \x12\x13\x14" \ 124 | "\x15\x16\x17\x20escaped!\a\b\n\r\t\b\f" 125 | cleaned_str = p.clean(input_str) 126 | self.assertEqual("I have escaped!", cleaned_str) 127 | 128 | def _test_clean_file(self, full_input_path, check_against, *options): 129 | output_path = p.clean_file(full_input_path, True, options) 130 | self.assertTrue(os.path.exists(output_path)) 131 | clean_content = p.get_file_contents(output_path) 132 | p.are_lists_equal(clean_content, check_against) 133 | 134 | def _get_test_data_for_option(self, raw_data, *options): 135 | clean_data = [] 136 | for d in raw_data: 137 | clean_data.append(p.clean(d)) 138 | return clean_data 139 | 140 | 141 | if __name__ == '__main__': 142 | unittest.main() 143 | -------------------------------------------------------------------------------- /tests/test_clean_numbers.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import preprocessor as p 4 | 5 | class PreprocessorTest(unittest.TestCase): 6 | def test_clean_number_1(self): 7 | tweet = "1231234" 8 | p.set_options(p.OPT.NUMBER) 9 | cleaned_tweeet = p.clean(tweet) 10 | self.assertEqual(cleaned_tweeet, '') 11 | 12 | def test_clean_number_2(self): 13 | tweet = "Lorem 198710 ipsum!" 14 | p.set_options(p.OPT.NUMBER) 15 | cleaned_tweeet = p.clean(tweet) 16 | self.assertEqual(cleaned_tweeet, 'Lorem ipsum!') 17 | 18 | def test_clean_number_3(self): 19 | tweet = "@lorem something 123213 ipsum" 20 | p.set_options(p.OPT.NUMBER) 21 | cleaned_tweeet = p.clean(tweet) 22 | self.assertEqual(cleaned_tweeet, '@lorem something ipsum') 23 | 24 | def test_clean_number_4(self): 25 | tweet = "123321 21398040 two numbers!" 26 | p.set_options(p.OPT.NUMBER) 27 | cleaned_tweeet = p.clean(tweet) 28 | self.assertEqual(cleaned_tweeet, 'two numbers!') 29 | 30 | def test_clean_number_5(self): 31 | tweet = "123,000 people" 32 | p.set_options(p.OPT.NUMBER) 33 | cleaned_tweeet = p.clean(tweet) 34 | self.assertEqual(cleaned_tweeet, 'people') 35 | 36 | def test_clean_number_6(self): 37 | tweet = "#lorem @loremipsum 900,000,000" 38 | p.set_options(p.OPT.NUMBER) 39 | cleaned_tweeet = p.clean(tweet) 40 | self.assertEqual(cleaned_tweeet, '#lorem @loremipsum') 41 | 42 | def test_clean_number_7(self): 43 | tweet = "World population will be 10,000,000,000 in 2100!" 44 | p.set_options(p.OPT.NUMBER) 45 | cleaned_tweeet = p.clean(tweet) 46 | self.assertEqual(cleaned_tweeet, 'World population will be in !') 47 | 48 | def test_clean_number_8(self): 49 | tweet = "lorem -987 ipsum" 50 | p.set_options(p.OPT.NUMBER) 51 | cleaned_tweeet = p.clean(tweet) 52 | self.assertEqual(cleaned_tweeet, 'lorem ipsum') 53 | 54 | def test_clean_number_9(self): 55 | tweet = "lorem -712,917,912,123 ipsum" 56 | p.set_options(p.OPT.NUMBER) 57 | cleaned_tweeet = p.clean(tweet) 58 | self.assertEqual(cleaned_tweeet, 'lorem ipsum') 59 | 60 | def test_clean_number_10(self): 61 | tweet = "World population will be 10,000,000,000 in 2100!" 62 | p.set_options(p.OPT.NUMBER) 63 | cleaned_tweeet = p.clean(tweet) 64 | self.assertEqual(cleaned_tweeet, 'World population will be in !') -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import random 5 | import unittest 6 | import platform 7 | import preprocessor as p 8 | 9 | 10 | class UtilsTest(unittest.TestCase): 11 | _test_dictionary = { 12 | "key": "value", 13 | "_key": "_val" 14 | } 15 | _test_file_contents = [ 16 | 'Preprocessor now supports files. https://github.com/s/preprocessor', 17 | '#preprocessing is a cruical part of @ML projects.', 18 | '@RT @Twitter raw text data usually has lots of #residue. http://t.co/g00gl', 19 | '#emoji #smiley 😀😍 https://emojipedia.org' 20 | ] 21 | _current_dir = "" 22 | _output_file_name_prefix = "test_utils_output_" 23 | _artifact_dir_name = "artifacts" 24 | 25 | def setUp(self): 26 | self._current_dir = os.path.dirname(__file__) 27 | self._artifacts_dir = os.path.join(self._current_dir, self._artifact_dir_name) 28 | 29 | def test_get_file_extension(self): 30 | self.assertEqual(p.get_file_extension("file.txt"), ".txt") 31 | self.assertEqual(p.get_file_extension("file.xcodeproj"), ".xcodeproj") 32 | self.assertEqual(p.get_file_extension(".gitignore"), ".gitignore") 33 | self.assertEqual(p.get_file_extension("..."), "...") 34 | self.assertEqual(p.get_file_extension(""), None) 35 | self.assertEqual(p.get_file_extension("_.abc"), ".abc") 36 | self.assertIsNone(p.get_file_extension("/a/b/c")) 37 | 38 | def test_write_to_output_file(self): 39 | # Test invalid directory 40 | invalid_dir = os.path.join(self._current_dir, "/a/b/c") 41 | self.assertRaises(ValueError, p.write_to_output_file, invalid_dir, []) 42 | 43 | # Test protected directories on macOS and Linux 44 | # (Travis CI disables Windows Defender) 45 | if not self._is_running_on_windows(): 46 | protected_directory = "/" 47 | output_file_name = self._output_file_name_prefix + "test_write_to_output_file.json" 48 | full_input_path = os.path.join(protected_directory, output_file_name) 49 | 50 | # Test file wasn't created due to protected directory 51 | self.assertRaises(OSError, p.write_to_json_file, full_input_path, {}) 52 | 53 | def test_write_to_json_file(self): 54 | # Test file was created 55 | output_path = self._write_test_contents_to_cur_dir(p.InputFileType.json) 56 | self.assertTrue(os.path.exists(output_path)) 57 | 58 | output_file_name = self._output_file_name_prefix + "dictionary.json" 59 | full_output_file_path = os.path.join(self._artifacts_dir, output_file_name) 60 | full_input_path = os.path.join(self._current_dir, full_output_file_path) 61 | output_path = p.write_to_json_file(full_input_path, self._test_dictionary) 62 | file_contents = p.get_json_file_contents(output_path) 63 | 64 | # Check the contents of written file is same as the one defined in this class 65 | self.assertEqual(file_contents["key"], self._test_dictionary["key"]) 66 | self.assertEqual(file_contents["_key"], self._test_dictionary["_key"]) 67 | 68 | def test_write_to_text_file(self): 69 | # Test file was created 70 | output_path = self._write_test_contents_to_cur_dir(p.InputFileType.text) 71 | self.assertTrue(os.path.exists(output_path)) 72 | 73 | file_contents = p.get_file_contents(output_path) 74 | # Check the contents of written file is same as the one defined in this class 75 | p.are_lists_equal(file_contents, self._test_file_contents) 76 | 77 | def test_generate_random_file_name(self): 78 | output_file_name = self._output_file_name_prefix + "test_generate_random_file_name.json" 79 | full_output_file_path = os.path.join(self._artifacts_dir, output_file_name) 80 | file_path = os.path.join(self._current_dir, full_output_file_path) 81 | gen_path = p.generate_random_file_name(file_path) 82 | self.assertNotEqual(file_path, gen_path) 83 | 84 | file_path_ext = p.get_file_extension(file_path) 85 | gen_path_ext = p.get_file_extension(gen_path) 86 | self.assertEqual(file_path_ext, gen_path_ext) 87 | 88 | l_path_excl_file = os.path.split(file_path) 89 | self.assertTrue(len(l_path_excl_file) > 0) 90 | 91 | r_path_excl_file = os.path.split(gen_path) 92 | self.assertTrue(len(r_path_excl_file) > 0) 93 | 94 | self.assertEqual(l_path_excl_file[0], r_path_excl_file[0]) 95 | 96 | def test_generate_random_alphanumeric_string(self): 97 | empty_str = p.generate_random_alphanumeric_string(str_length=0) 98 | self.assertEqual(len(empty_str), 0) 99 | 100 | output_str = p.generate_random_alphanumeric_string(str_length=100) 101 | self.assertEqual(len(output_str), 100) 102 | 103 | str_len = random.choice(range(4, 32)) 104 | iteration_count = random.choice(range(1, 128)) 105 | for i in range(1, iteration_count): 106 | lhs = p.generate_random_alphanumeric_string(str_length=str_len) 107 | rhs = p.generate_random_alphanumeric_string(str_length=str_len) 108 | self.assertNotEqual(lhs, rhs) 109 | 110 | def test_are_lists_equal(self): 111 | self.assertTrue(p.are_lists_equal([], [])) 112 | self.assertFalse(p.are_lists_equal([], [1])) 113 | self.assertRaises(ValueError, p.are_lists_equal, "", []) 114 | self.assertTrue(p.are_lists_equal([[]], [])) 115 | self.assertTrue(p.are_lists_equal([[2]], [2])) 116 | self.assertTrue(p.are_lists_equal(["Test"], ["Test"])) 117 | 118 | def _is_running_on_windows(self): 119 | return not platform.system() in ["Linux", "Darwin"] 120 | 121 | def _write_test_contents_to_cur_dir(self, ext): 122 | output_file_name = self._output_file_name_prefix + "_write_test_contents_to_cur_dir" + ext 123 | full_input_path = os.path.join(self._artifacts_dir, output_file_name) 124 | if p.InputFileType.json == ext: 125 | return p.write_to_json_file(full_input_path, self._test_file_contents) 126 | elif p.InputFileType.text == ext: 127 | return p.write_to_text_file(full_input_path, self._test_file_contents) 128 | 129 | 130 | if __name__ == '__main__': 131 | unittest.main() 132 | --------------------------------------------------------------------------------