├── .gitignore ├── .readthedocs.yaml ├── COPYING ├── COPYING.LESSER ├── MANIFEST.in ├── README ├── README.rst ├── docs ├── conf.py ├── index.rst ├── intro.rst ├── ngram.rst ├── releasenotes.rst └── tutorial.rst ├── ngram.py ├── pyproject.toml ├── scripts └── csvjoin.py ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_csvjoin.py └── test_ngram.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .cache 3 | *.egg-info 4 | *.pyc 5 | *.wpu 6 | /.tox 7 | /.vscode 8 | /build 9 | /dist 10 | /docs/build 11 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Build documentation in the docs/ directory with Sphinx 9 | sphinx: 10 | configuration: docs/conf.py 11 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING 2 | include COPYING.LESSER 3 | include tox.ini 4 | graft docs 5 | prune docs/build 6 | graft tests 7 | global-exclude *.pyc 8 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | The NGram class extends the Python 'set' class with efficient 2 | fuzzy search for members by means of an N-gram similarity measure. 3 | It also has static methods to compare a pair of strings. 4 | 5 | The N-grams are character based not word-based, and the class does not 6 | implement a language model, merely searching for members by string similarity. 7 | 8 | See the `documentation`_, which includes a tutorial and release notes. 9 | 10 | Use the `GitHub issue tracker`_ to report issues. 11 | 12 | Installation 13 | ============ 14 | 15 | To install python-ngram from `PyPI`_:: 16 | 17 | pip install ngram 18 | 19 | How does it work? 20 | ================= 21 | 22 | The set stores arbitrary items, but for non-string items a `key` function 23 | (such as `str`) must be specified to provide a string represenation. The key 24 | function can also be used to normalise string items (e.g. lower-casing) prior 25 | to N-gram indexing. 26 | 27 | To index a string it pads the string with a specified dummy character, then 28 | splits it into overlapping substrings of N (default N=3) characters in length 29 | and associates each N-gram to the items that use it. 30 | 31 | To find items similar to a query string, it splits the query into N-grams, 32 | collects all items sharing at least one N-gram with the query, 33 | and ranks the items by score based on the ratio of shared to unshared 34 | N-grams between strings. 35 | 36 | History 37 | ======= 38 | 39 | In 2007, Michel Albert (exhuma) wrote the python-ngram module based on Perl's 40 | `String::Trigram`_ module by Tarek Ahmed, and committed the code for 2.0.0b2 to 41 | a now-disused `Sourceforge`_ subversion repo. 42 | 43 | Since late 2008, Graham Poulter has maintained python-ngram, initially refactoring 44 | it to build on the `set` class, and also adding features, documentation, tests, 45 | performance improvements and Python 3 support. 46 | 47 | Development 48 | =========== 49 | 50 | Development takes place on `Github`_. On checking out the repo run `tox` to build 51 | the Sphinx documentation and run tests. Run `pip install -e .` to install the module 52 | in editable mode, inside a virtualenv. 53 | 54 | .. _documentation: https://python-ngram.readthedocs.io/en/latest/ 55 | .. _GitHub: http://github.com/gpoulter/python-ngram 56 | .. _GitHub issue tracker: https://github.com/gpoulter/python-ngram/issues 57 | .. _PyPI: http://pypi.python.org/pypi/ngram 58 | .. _String::Trigram: http://search.cpan.org/dist/String-Trigram/ 59 | .. _Sourceforge: https://sourceforge.net/projects/python-ngram/ 60 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | README -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # NGram documentation build configuration file. 2 | 3 | # Add any Sphinx extension module names here, as strings. They can be extensions 4 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 5 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] 6 | 7 | # The suffix of source filenames. 8 | source_suffix = '.rst' 9 | 10 | # The human-readable project name 11 | project = u'Python NGram' 12 | 13 | # The short X.Y version. 14 | version = '4.0' 15 | 16 | # The full version, including alpha/beta/rc tags. 17 | release = '4.0.3' 18 | 19 | # Language the docs are written in. 20 | language = 'en' 21 | 22 | # Copyright byline. 23 | copyright = 'Graham Poulter, Michel Albert 2008-2021' 24 | 25 | # List of directories, relative to source directory, that shouldn't be searched 26 | # for source files. 27 | exclude_trees = ['build'] 28 | 29 | # The name of the Pygments (syntax highlighting) style to use. 30 | pygments_style = 'sphinx' 31 | 32 | # Name (excluding extension) of root document. 33 | root_doc = 'index' -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Python NGram documentation 2 | ++++++++++++++++++++++++++ 3 | 4 | .. toctree:: 5 | :maxdepth: 3 6 | 7 | intro 8 | tutorial 9 | ngram 10 | releasenotes 11 | 12 | -------------------------------------------------------------------------------- /docs/intro.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | Introduction 3 | ============== 4 | 5 | .. include:: ../README 6 | 7 | License 8 | ======= 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Lesser General Public License as published 12 | by the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see 22 | 23 | * :download:`Text of GPLv3 <../COPYING>` 24 | * :download:`Text of LGPLv3 <../COPYING.LESSER>` 25 | 26 | Indices and tables 27 | ================== 28 | 29 | * :ref:`genindex` 30 | * :ref:`modindex` 31 | * :ref:`search` 32 | 33 | -------------------------------------------------------------------------------- /docs/ngram.rst: -------------------------------------------------------------------------------- 1 | ============================ 2 | NGram Module Documentation 3 | ============================ 4 | 5 | .. automodule:: ngram 6 | :members: 7 | 8 | -------------------------------------------------------------------------------- /docs/releasenotes.rst: -------------------------------------------------------------------------------- 1 | Release Notes 2 | ============= 3 | 4 | Version 4.0.3 5 | ------------- 6 | Released 2021-09-15 7 | 8 | * Fixed the setup.cfg 9 | 10 | Version 4.0.1 11 | ------------- 12 | Released 2021-09-10 13 | 14 | * Switched documentation host to ReadTheDocs because sphinx_upload stopped working. 15 | 16 | Version 4.0.0 17 | ------------- 18 | Released 2021-09-10 19 | 20 | * Removed Python 2.7 support since 2to3 support is removed from recent setuptools. 21 | 22 | Version 3.3.2 23 | ------------- 24 | Released 2017-06-20 25 | 26 | * Fixed bug in remove and pop attempting to delete an ngram multiple times. 27 | * Add DeprecationWarning for use of iconv param, ngrams method, ngrams_pad method. 28 | * Fixed csvjoin_test to run on Windows. 29 | * Fixed doctests to support dictionary random iteration order. 30 | 31 | Version 3.3.0 32 | ------------- 33 | Released 2012-06-29 34 | 35 | NEW FEATURES 36 | * Correct support for remaining set methods: `pop`, `clear`, `union`, `intersection`, `difference`, `symmetric_difference` 37 | * Can provide alternate `items` to the `copy` method 38 | 39 | IMPROVEMENTS 40 | * Update license from LGPL to LGPL version 3 41 | * Revised readme to work with GitHub, PyPI and generated docs. 42 | * Tox to run all doctests, pass under 2.7 and 3.2 43 | 44 | BUG FIXES 45 | * Fix unused threshold param in `searchitem` method 46 | * Fix intersection_update to accept multiple other iterables 47 | 48 | Version 3.2.1 49 | ------------- 50 | Released 2012-06-28 51 | 52 | * Fix bug in symmetric_difference_update method 53 | * Update release notes / changelog 54 | * Update tutorial 55 | 56 | Version 3.2.0 57 | ------------- 58 | Released 2012-06-25 59 | 60 | NEW FEATURES 61 | * "csvjoin" script performs SQL-like join between CSV tables based on string similarity. 62 | * NGram instances can now be pickled/unpickled (added __reduce__) 63 | * Add searchitem method to search by item (search method takes a string) 64 | * Add find and finditem methods to return 1 result instead of a list. 65 | 66 | BREAKING CHANGES 67 | * iconv parameter is now the "key" parameter (matches the sorted() builtin) 68 | * qconv parameter no longer exists: use searchitem method to query by item 69 | * the `ngrams_pad` method is deprecated for new `split` and `splititem` methods 70 | * the `ngrams` method is deprecated (equivalent `_split` is for internal use) 71 | 72 | OTHER IMPROVEMENTS 73 | * Converted Mercurial repo to Git 74 | * Corrected indentation from 3 to 4 spaces 75 | * Added tox to run tests on Python 2.7 and 3.2 76 | 77 | Version 3.1.0 78 | ------------- 79 | Released 2009-12-07 80 | 81 | NEW FEATURES 82 | * Python 3 support via 2to3 83 | * Sphinx documentation generation 84 | * Tutorial documentation 85 | 86 | BREAKING CHANGES 87 | * str_item and str_query params are now iconv and qconv 88 | 89 | BUG FIXES 90 | * Integer division bug (e.g. arises when warp is 2 not 2.0) 91 | 92 | MINOR CHANGES 93 | * Setuptools replaced by Distribute (for Python 3) 94 | * Docstrings now reStructuredText for Sphinx 95 | 96 | Version 3.0.0 97 | ------------- 98 | Released 2009-07-03. 99 | 100 | This was a major refactoring without back-compatibility. 101 | 102 | NEW FEATURES 103 | * Accepts any hashable item - no longer limited to strings. 104 | * Re-written as subclass of set, gaining all set operations. 105 | * Docstrings added. Using Epydoc API doc generator. 106 | 107 | IMPROVEMENTS 108 | * Eliminated innermost level of dictionaries, reducing memory usage. 109 | * Revised to use Python 2.6 idioms. Losing Python 2.2 compatibility. 110 | * Renamed things to follow PEP 8 111 | * Refactored the NGram class (new method decomposition) 112 | 113 | 114 | Version 2.0.0b2 115 | --------------- 116 | Released 2007-10-23. 117 | 118 | This was the code committed to Subversion by Exhuma. 119 | 120 | 121 | -------------------------------------------------------------------------------- /docs/tutorial.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | Tutorial 3 | ========== 4 | 5 | Comparing and searching strings 6 | =============================== 7 | 8 | Compare two strings using :meth:`~ngram.NGram.compare`: 9 | 10 | .. doctest:: 11 | 12 | >>> import ngram 13 | >>> ngram.NGram.compare('Ham','Spam',N=1) 14 | 0.4 15 | 16 | The :class:`~ngram.NGram` class extends the builtin `set` class with the 17 | ability to search for members by n-gram similarity. 18 | 19 | Use :meth:`~ngram.NGram.search` to return similar items in a set, 20 | and :meth:`~ngram.NGram.find` to only return the most similar item: 21 | 22 | .. doctest:: 23 | 24 | >>> G = ngram.NGram(['joe','joseph','jon','john','sally']) 25 | >>> G.search('jon') 26 | [('jon', 1.0), ('john', 0.375), ('joe', 0.25), ('joseph', 0.18181818181818182)] 27 | >>> G.search('jon', threshold=0.3) 28 | [('jon', 1.0), ('john', 0.375)] 29 | >>> G.find('jose') 30 | 'joseph' 31 | 32 | Transforming items 33 | ================== 34 | 35 | By default no transformation is done, so items must be strings. By passing a `key` function, 36 | similar to the `key` parameter of the `sorted` builtin, arbitrary items can be indexed. 37 | For non-string items, generally pass `str` or `unicode` as the key function. 38 | 39 | Below, we define a key function to index the lower-case version of a string, and use 40 | the key, pad and ngrams methods to examine the internal representations: 41 | 42 | .. doctest:: 43 | 44 | >>> def lower(s): 45 | ... return s.lower() 46 | >>> G = ngram.NGram(key=lower) 47 | >>> G.key('AbC') 48 | 'abc' 49 | >>> G.pad('abc') 50 | '$$abc$$' 51 | >>> list(G.split('abc')) 52 | ['$$a', '$ab', 'abc', 'bc$', 'c$$'] 53 | 54 | Searching with a lowercase query returns results, but there is no match if the 55 | query contains capitals: 56 | 57 | .. doctest:: 58 | 59 | >>> G.add('AbC') 60 | >>> G.search('abcd') 61 | [('AbC', 0.375)] 62 | >>> G.find('abcd') 63 | 'AbC' 64 | >>> G.search('AbC') == [] 65 | True 66 | >>> G.find('AbC') == None 67 | True 68 | 69 | We can either lowercase the query, or use the "searchitem" or "finditem" 70 | methods that apply the key function to the query before searching: 71 | 72 | .. doctest:: 73 | 74 | >>> G.search('AbCD'.lower()) 75 | [('AbC', 0.375)] 76 | >>> G.find(lower('AbCD')) 77 | 'AbC' 78 | >>> G.searchitem('AbCD') 79 | [('AbC', 0.375)] 80 | >>> G.finditem('AbCD') 81 | 'AbC' 82 | 83 | So long as the function can be found in `__main__` or imported, NGram instances can be pickled: 84 | 85 | .. doctest:: 86 | 87 | >>> import pickle 88 | >>> pickle.dumps(G) #doctest: +IGNORE_EXCEPTION_DETAIL 89 | Traceback (most recent call last): 90 | ... 91 | PicklingError: Can't pickle : it's not found as __main__.lower 92 | >>> import string 93 | >>> H1 = ngram.NGram(['ab cd'], key=string.capwords) 94 | >>> text = pickle.dumps(H1) 95 | >>> H2 = pickle.loads(text) 96 | >>> list(H1) 97 | ['ab cd'] 98 | >>> list(H2) 99 | ['ab cd'] 100 | 101 | The key function can perform complex transformations: 102 | 103 | .. doctest:: 104 | 105 | >>> G = ngram.NGram(key=lambda x:(" ".join(x)).lower()) 106 | >>> G.add(("Joe","Bloggs")) 107 | >>> G.search("jeo blogger") 108 | [(('Joe', 'Bloggs'), 0.25)] 109 | >>> G.searchitem(("Jeo", "Blogger")) 110 | [(('Joe', 'Bloggs'), 0.25)] 111 | 112 | 113 | Set Operations 114 | ============== 115 | 116 | The `update`, `discard`, `difference_update`, `intersection_update` and `symmetric_difference` update 117 | methods from the builtin `set` class have been overridden to maintain the integrity of the 118 | NGram index when performing them. These take any iterable as argument, including another 119 | NGram instance. 120 | 121 | .. doctest:: 122 | 123 | >>> G = ngram.NGram(['joe','joseph','jon','john','sally']) 124 | >>> G.update(['jonathan']) 125 | >>> sorted(list(G)) 126 | ['joe', 'john', 'jon', 'jonathan', 'joseph', 'sally'] 127 | >>> G.discard('sally') 128 | >>> sorted(list(G)) 129 | ['joe', 'john', 'jon', 'jonathan', 'joseph'] 130 | >>> G.difference_update(ngram.NGram(['joe'])) 131 | >>> sorted(list(G)) 132 | ['john', 'jon', 'jonathan', 'joseph'] 133 | >>> G.intersection_update(['james', 'joseph', 'joe', 'jon']) 134 | >>> sorted(list(G)) 135 | ['jon', 'joseph'] 136 | >>> G.symmetric_difference_update(ngram.NGram(['jimmy', 'jon'])) 137 | >>> sorted(list(G)) 138 | ['jimmy', 'joseph'] 139 | 140 | 141 | Multi-byte characters 142 | ===================== 143 | 144 | Use Python 3 strings (unicode) where possible. 145 | 146 | It is possible to use NGram with bytes, but only with single-byte 147 | encodings, and you must also use a byte string as the padding 148 | character: 149 | 150 | .. doctest:: 151 | 152 | >>> index = ngram.NGram(N=3, pad_char=b'$', pad_len=2) 153 | >>> list(index.split(b'abc')) 154 | [b'$$a', b'$ab', b'abc', b'bc$', b'c$$'] 155 | 156 | NGram will not work correctly with UTF-8 encoded bytes, because 157 | characters like é (code point 0xE9) will encode to multiple bytes as 158 | ``b'\xc3\xa9'`` and be treated as 2 separate characters. 159 | 160 | A unicode string ``'\xe9'`` will be treated correctly as a single 161 | character. -------------------------------------------------------------------------------- /ngram.py: -------------------------------------------------------------------------------- 1 | """ 2 | :mod:`ngram` -- A set class that supports lookup by N-gram string similarity 3 | ============================================================================ 4 | """ 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published 8 | # by the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with this program. If not, see 18 | 19 | import warnings 20 | 21 | class NGram(set): 22 | """A set that supports searching for members by N-gram string similarity. 23 | 24 | In Python 2, items should be `unicode` string or a plain ASCII `str` 25 | (bytestring) - do not use UTF-8 or other multi-byte encodings, because 26 | multi-byte characters will be split up. 27 | 28 | :type threshold: float in 0.0 ... 1.0 29 | 30 | :param threshold: minimum similarity for a string to be considered a match. 31 | 32 | :type warp: float in 1.0 ... 3.0 33 | 34 | :param warp: use warp greater than 1.0 to increase the similarity of \ 35 | shorter string pairs. 36 | 37 | :type items: [item, ...] 38 | 39 | :param items: iteration of items to index for N-gram search. 40 | 41 | :type N: int >= 2 42 | 43 | :param N: number of characters per n-gram. 44 | 45 | :type pad_len: int in 0 ... N-1 46 | 47 | :param pad_len: how many characters padding to add (defaults to N-1). 48 | 49 | :type pad_char: str or unicode 50 | 51 | :param pad_char: character to use for padding. Default is '$', but \ 52 | consider using the\\ non-breaking space character, ``u'\\xa0'`` \ 53 | (``u"\\u00A0"``). 54 | 55 | :type key: function(item) -> str/unicode 56 | 57 | :param key: Function to convert items into string, default is no \ 58 | conversion. Recommended to use `str` or `unicode` for non-string items. \ 59 | Using anonymous function prevents NGram class from being pickled. 60 | 61 | Instance variables: 62 | 63 | :ivar _grams: For each n-gram, the items containing it and the number of \ 64 | times\\ the n-gram occurs in the item as ``{str:{item:int, ...}, ...}``. 65 | 66 | :ivar length: maps items to length of the padded string representations \ 67 | as ``{item:int, ...}``. 68 | """ 69 | 70 | def __init__(self, items=None, threshold=0.0, warp=1.0, key=None, 71 | N=3, pad_len=None, pad_char='$', **kwargs): 72 | super(NGram, self).__init__() 73 | if not (0 <= threshold <= 1): 74 | raise ValueError("threshold out of range 0.0 to 1.0: " 75 | + repr(threshold)) 76 | if not (1.0 <= warp <= 3.0): 77 | raise ValueError( 78 | "warp out of range 1.0 to 3.0: " + repr(warp)) 79 | if not N >= 1: 80 | raise ValueError("N out of range (should be N >= 1): " + repr(N)) 81 | if pad_len is None: 82 | pad_len = N - 1 83 | if not (0 <= pad_len < N): 84 | raise ValueError("pad_len out of range: " + repr(pad_len)) 85 | if not len(pad_char) == 1: 86 | raise ValueError( 87 | "pad_char is not single character: " + repr(pad_char)) 88 | if key is not None and not callable(key): 89 | raise ValueError("key is not a function: " + repr(key)) 90 | self.threshold = threshold 91 | self.warp = warp 92 | self.N = N 93 | self._pad_len = pad_len 94 | self._pad_char = pad_char 95 | self._padding = pad_char * pad_len # derive a padding string 96 | # compatibility shim for 3.1 iconv parameter 97 | if 'iconv' in kwargs: 98 | self._key = kwargs.pop('iconv') 99 | warnings.warn('"iconv" parameter deprecated, use "key" instead.', DeprecationWarning) 100 | # no longer support 3.1 qconv parameter 101 | if 'qconv' in kwargs: 102 | raise ValueError('qconv query conversion parameter unsupported. ' 103 | 'Please process query to a string before calling .search') 104 | self._key = key 105 | self._grams = {} 106 | self.length = {} 107 | if items: 108 | self.update(items) 109 | 110 | def __reduce__(self): 111 | """Return state information for pickling, no references to this 112 | instance. The key function must be None, a builtin function, or 113 | a named module-level function. 114 | 115 | >>> from ngram import NGram 116 | >>> n = NGram([0xDEAD, 0xBEEF], key=hex) 117 | >>> import pickle 118 | >>> p = pickle.dumps(n) 119 | >>> m = pickle.loads(p) 120 | >>> sorted(list(m)) 121 | [48879, 57005] 122 | """ 123 | return NGram, (list(self), self.threshold, self.warp, self._key, 124 | self.N, self._pad_len, self._pad_char) 125 | 126 | def copy(self, items=None): 127 | """Return a new NGram object with the same settings, and 128 | referencing the same items. Copy is shallow in that 129 | each item is not recursively copied. Optionally specify 130 | alternate items to populate the copy. 131 | 132 | >>> from ngram import NGram 133 | >>> from copy import deepcopy 134 | >>> n = NGram(['eggs', 'spam']) 135 | >>> m = n.copy() 136 | >>> m.add('ham') 137 | >>> sorted(list(n)) 138 | ['eggs', 'spam'] 139 | >>> sorted(list(m)) 140 | ['eggs', 'ham', 'spam'] 141 | >>> p = n.copy(['foo', 'bar']) 142 | >>> sorted(list(p)) 143 | ['bar', 'foo'] 144 | """ 145 | return NGram(items if items is not None else self, 146 | self.threshold, self.warp, self._key, 147 | self.N, self._pad_len, self._pad_char) 148 | 149 | def key(self, item): 150 | """Get the key string for the item. 151 | 152 | >>> from ngram import NGram 153 | >>> n = NGram(key=lambda x:x[1]) 154 | >>> n.key((3,"ham")) 155 | 'ham' 156 | """ 157 | return self._key(item) if self._key else item 158 | 159 | def pad(self, string): 160 | """Pad a string in preparation for splitting into ngrams. 161 | 162 | >>> from ngram import NGram 163 | >>> n = NGram() 164 | >>> n.pad('ham') 165 | '$$ham$$' 166 | """ 167 | return self._padding + string + self._padding 168 | 169 | def _split(self, string): 170 | """Iterates over the ngrams of a string (no padding). 171 | 172 | >>> from ngram import NGram 173 | >>> n = NGram() 174 | >>> list(n._split("hamegg")) 175 | ['ham', 'ame', 'meg', 'egg'] 176 | """ 177 | for i in range(len(string) - self.N + 1): 178 | yield string[i:i + self.N] 179 | 180 | def split(self, string): 181 | """Pads a string and iterates over its ngrams. 182 | 183 | >>> from ngram import NGram 184 | >>> n = NGram() 185 | >>> list(n.split("ham")) 186 | ['$$h', '$ha', 'ham', 'am$', 'm$$'] 187 | """ 188 | return self._split(self.pad(string)) 189 | 190 | def ngrams(self, string): 191 | """Alias for 3.1 compatibility, please set pad_len=0 and use split.""" 192 | warnings.warn('Method ngram deprecated, use method split with pad_len=0 instead.', DeprecationWarning) 193 | return self._split(string) 194 | 195 | def ngrams_pad(self, string): 196 | """Alias for 3.1 compatibility, please use split instead.""" 197 | warnings.warn('Method ngrams_pad deprecated, use method split instead.', DeprecationWarning) 198 | return self.split(string) 199 | 200 | def splititem(self, item): 201 | """Pads the string key of an item and iterates over its ngrams. 202 | 203 | >>> from ngram import NGram 204 | >>> n = NGram(key=lambda x:x[1]) 205 | >>> item = (3,"ham") 206 | >>> list(n.splititem(item)) 207 | ['$$h', '$ha', 'ham', 'am$', 'm$$'] 208 | """ 209 | return self.split(self.key(item)) 210 | 211 | def add(self, item): 212 | """Add an item to the N-gram index (if it has not already been added). 213 | 214 | >>> from ngram import NGram 215 | >>> n = NGram() 216 | >>> n.add("ham") 217 | >>> list(n) 218 | ['ham'] 219 | >>> n.add("spam") 220 | >>> sorted(list(n)) 221 | ['ham', 'spam'] 222 | """ 223 | if item not in self: 224 | # Add the item to the base set 225 | super(NGram, self).add(item) 226 | # Record length of padded string 227 | padded_item = self.pad(self.key(item)) 228 | self.length[item] = len(padded_item) 229 | for ngram in self._split(padded_item): 230 | # Add a new n-gram and string to index if necessary 231 | self._grams.setdefault(ngram, {}).setdefault(item, 0) 232 | # Increment number of times the n-gram appears in the string 233 | self._grams[ngram][item] += 1 234 | 235 | def remove(self, item): 236 | """Remove an item from the set. Inverts the add operation. 237 | 238 | >>> from ngram import NGram 239 | >>> n = NGram(['spam', 'eggs']) 240 | >>> n.remove('spam') 241 | >>> list(n) 242 | ['eggs'] 243 | """ 244 | if item in self: 245 | super(NGram, self).remove(item) 246 | del self.length[item] 247 | for ngram in set(self.splititem(item)): 248 | del self._grams[ngram][item] 249 | 250 | def pop(self): 251 | """Remove and return an arbitrary set element. 252 | Raises KeyError if the set is empty. 253 | 254 | >>> from ngram import NGram 255 | >>> n = NGram(['spam', 'eggs']) 256 | >>> x = n.pop() 257 | >>> len(n) 258 | 1 259 | """ 260 | item = super(NGram, self).pop() 261 | del self.length[item] 262 | for ngram in set(self.splititem(item)): 263 | del self._grams[ngram][item] 264 | return item 265 | 266 | def items_sharing_ngrams(self, query): 267 | """Retrieve the subset of items that share n-grams the query string. 268 | 269 | :param query: look up items that share N-grams with this string. 270 | :return: mapping from matched string to the number of shared N-grams. 271 | 272 | >>> from ngram import NGram 273 | >>> n = NGram(["ham","spam","eggs"]) 274 | >>> sorted(n.items_sharing_ngrams("mam").items()) 275 | [('ham', 2), ('spam', 2)] 276 | """ 277 | # From matched string to number of N-grams shared with query string 278 | shared = {} 279 | # Dictionary mapping n-gram to string to number of occurrences of that 280 | # ngram in the string that remain to be matched. 281 | remaining = {} 282 | for ngram in self.split(query): 283 | try: 284 | for match, count in self._grams[ngram].items(): 285 | remaining.setdefault(ngram, {}).setdefault(match, count) 286 | # match as many occurrences as exist in matched string 287 | if remaining[ngram][match] > 0: 288 | remaining[ngram][match] -= 1 289 | shared.setdefault(match, 0) 290 | shared[match] += 1 291 | except KeyError: 292 | pass 293 | return shared 294 | 295 | def searchitem(self, item, threshold=None): 296 | """Search the index for items whose key exceeds the threshold 297 | similarity to the key of the given item. 298 | 299 | :return: list of pairs of (item, similarity) by decreasing similarity. 300 | 301 | >>> from ngram import NGram 302 | >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG"), 303 | ... (3, "SPANN")], key=lambda x:x[1]) 304 | >>> sorted(n.searchitem((2, "SPA"), 0.35)) 305 | [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] 306 | """ 307 | return self.search(self.key(item), threshold) 308 | 309 | def search(self, query, threshold=None): 310 | """Search the index for items whose key exceeds threshold 311 | similarity to the query string. 312 | 313 | :param query: returned items will have at least `threshold` \ 314 | similarity to the query string. 315 | 316 | :return: list of pairs of (item, similarity) by decreasing similarity. 317 | 318 | >>> from ngram import NGram 319 | >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG")], key=lambda x:x[1]) 320 | >>> sorted(n.search("SPA")) 321 | [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] 322 | >>> n.search("M") 323 | [((0, 'SPAM'), 0.125)] 324 | >>> n.search("EG") 325 | [((2, 'EG'), 1.0)] 326 | """ 327 | threshold = threshold if threshold is not None else self.threshold 328 | results = [] 329 | # Identify possible results 330 | for match, samegrams in self.items_sharing_ngrams(query).items(): 331 | allgrams = (len(self.pad(query)) 332 | + self.length[match] - (2 * self.N) - samegrams + 2) 333 | similarity = self.ngram_similarity(samegrams, allgrams, self.warp) 334 | if similarity >= threshold: 335 | results.append((match, similarity)) 336 | # Sort results by decreasing similarity 337 | results.sort(key=lambda x: x[1], reverse=True) 338 | return results 339 | 340 | def finditem(self, item, threshold=None): 341 | """Return most similar item to the provided one, or None if 342 | nothing exceeds the threshold. 343 | 344 | >>> from ngram import NGram 345 | >>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")], 346 | ... key=lambda x:x[1].lower()) 347 | >>> n.finditem((3, 'Hom')) 348 | (1, 'Ham') 349 | >>> n.finditem((4, "Oggsy")) 350 | (2, 'Eggsy') 351 | >>> n.finditem((4, "Oggsy"), 0.8) 352 | """ 353 | results = self.searchitem(item, threshold) 354 | if results: 355 | return results[0][0] 356 | else: 357 | return None 358 | 359 | def find(self, query, threshold=None): 360 | """Simply return the best match to the query, None on no match. 361 | 362 | >>> from ngram import NGram 363 | >>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1) 364 | >>> n.find('Hom') 365 | 'Ham' 366 | >>> n.find("Spom") 367 | 'Spam' 368 | >>> n.find("Spom", 0.8) 369 | """ 370 | results = self.search(query, threshold) 371 | if results: 372 | return results[0][0] 373 | else: 374 | return None 375 | 376 | @staticmethod 377 | def ngram_similarity(samegrams, allgrams, warp=1.0): 378 | """Similarity for two sets of n-grams. 379 | 380 | :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \ 381 | "all n-grams", `d` is "different n-grams" and `e` is the warp. 382 | 383 | :param samegrams: number of n-grams shared by the two strings. 384 | 385 | :param allgrams: total of the distinct n-grams across the two strings. 386 | :return: similarity in the range 0.0 to 1.0. 387 | 388 | >>> from ngram import NGram 389 | >>> NGram.ngram_similarity(5, 10) 390 | 0.5 391 | >>> NGram.ngram_similarity(5, 10, warp=2) 392 | 0.75 393 | >>> NGram.ngram_similarity(5, 10, warp=3) 394 | 0.875 395 | >>> NGram.ngram_similarity(2, 4, warp=2) 396 | 0.75 397 | >>> NGram.ngram_similarity(3, 4) 398 | 0.75 399 | """ 400 | if abs(warp - 1.0) < 1e-9: 401 | similarity = float(samegrams) / allgrams 402 | else: 403 | diffgrams = float(allgrams - samegrams) 404 | similarity = ((allgrams ** warp - diffgrams ** warp) 405 | / (allgrams ** warp)) 406 | return similarity 407 | 408 | @staticmethod 409 | def compare(s1, s2, **kwargs): 410 | """Compares two strings and returns their similarity. 411 | 412 | :param s1: first string 413 | :param s2: second string 414 | :param kwargs: additional keyword arguments passed to __init__. 415 | :return: similarity between 0.0 and 1.0. 416 | 417 | >>> from ngram import NGram 418 | >>> NGram.compare('spa', 'spam') 419 | 0.375 420 | >>> NGram.compare('ham', 'bam') 421 | 0.25 422 | >>> NGram.compare('spam', 'pam') #N=2 423 | 0.375 424 | >>> NGram.compare('ham', 'ams', N=1) 425 | 0.5 426 | """ 427 | if s1 is None or s2 is None: 428 | if s1 == s2: 429 | return 1.0 430 | return 0.0 431 | try: 432 | return NGram([s1], **kwargs).search(s2)[0][1] 433 | except IndexError: 434 | return 0.0 435 | 436 | ### Set operations implemented on top of NGram add/remove 437 | 438 | def update(self, items): 439 | """Update the set with new items. 440 | 441 | >>> from ngram import NGram 442 | >>> n = NGram(["spam"]) 443 | >>> n.update(["eggs"]) 444 | >>> sorted(list(n)) 445 | ['eggs', 'spam'] 446 | """ 447 | for item in items: 448 | self.add(item) 449 | 450 | def discard(self, item): 451 | """Remove an element from a set if it is a member. 452 | 453 | If the element is not a member, do nothing. 454 | 455 | >>> from ngram import NGram 456 | >>> n = NGram(['spam', 'eggs']) 457 | >>> n.discard('spam') 458 | >>> n.discard('ham') 459 | >>> list(n) 460 | ['eggs'] 461 | """ 462 | if item in self: 463 | self.remove(item) 464 | 465 | def clear(self): 466 | """Remove all elements from this set. 467 | 468 | >>> from ngram import NGram 469 | >>> n = NGram(['spam', 'eggs']) 470 | >>> sorted(list(n)) 471 | ['eggs', 'spam'] 472 | >>> n.clear() 473 | >>> list(n) 474 | [] 475 | """ 476 | super(NGram, self).clear() 477 | self._grams = {} 478 | self.length = {} 479 | 480 | def union(self, *others): 481 | """Return the union of two or more sets as a new set. 482 | 483 | >>> from ngram import NGram 484 | >>> a = NGram(['spam', 'eggs']) 485 | >>> b = NGram(['spam', 'ham']) 486 | >>> sorted(list(a.union(b))) 487 | ['eggs', 'ham', 'spam'] 488 | """ 489 | return self.copy(super(NGram, self).union(*others)) 490 | 491 | def difference(self, *others): 492 | """Return the difference of two or more sets as a new set. 493 | 494 | >>> from ngram import NGram 495 | >>> a = NGram(['spam', 'eggs']) 496 | >>> b = NGram(['spam', 'ham']) 497 | >>> list(a.difference(b)) 498 | ['eggs'] 499 | """ 500 | return self.copy(super(NGram, self).difference(*others)) 501 | 502 | def difference_update(self, other): 503 | """Remove from this set all elements from `other` set. 504 | 505 | >>> from ngram import NGram 506 | >>> n = NGram(['spam', 'eggs']) 507 | >>> other = set(['spam']) 508 | >>> n.difference_update(other) 509 | >>> list(n) 510 | ['eggs'] 511 | """ 512 | for item in other: 513 | self.discard(item) 514 | 515 | def intersection(self, *others): 516 | """Return the intersection of two or more sets as a new set. 517 | 518 | >>> from ngram import NGram 519 | >>> a = NGram(['spam', 'eggs']) 520 | >>> b = NGram(['spam', 'ham']) 521 | >>> list(a.intersection(b)) 522 | ['spam'] 523 | """ 524 | return self.copy(super(NGram, self).intersection(*others)) 525 | 526 | def intersection_update(self, *others): 527 | """Update the set with the intersection of itself and other sets. 528 | 529 | >>> from ngram import NGram 530 | >>> n = NGram(['spam', 'eggs']) 531 | >>> other = set(['spam', 'ham']) 532 | >>> n.intersection_update(other) 533 | >>> list(n) 534 | ['spam'] 535 | """ 536 | self.difference_update(super(NGram, self).difference(*others)) 537 | 538 | def symmetric_difference(self, other): 539 | """Return the symmetric difference of two sets as a new set. 540 | 541 | >>> from ngram import NGram 542 | >>> a = NGram(['spam', 'eggs']) 543 | >>> b = NGram(['spam', 'ham']) 544 | >>> sorted(list(a.symmetric_difference(b))) 545 | ['eggs', 'ham'] 546 | """ 547 | return self.copy(super(NGram, self).symmetric_difference(other)) 548 | 549 | def symmetric_difference_update(self, other): 550 | """Update the set with the symmetric difference of itself and `other`. 551 | 552 | >>> from ngram import NGram 553 | >>> n = NGram(['spam', 'eggs']) 554 | >>> other = set(['spam', 'ham']) 555 | >>> n.symmetric_difference_update(other) 556 | >>> sorted(list(n)) 557 | ['eggs', 'ham'] 558 | """ 559 | intersection = super(NGram, self).intersection(other) 560 | self.update(other) # add items present in other 561 | self.difference_update(intersection) # remove items present in both 562 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" -------------------------------------------------------------------------------- /scripts/csvjoin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | Left similarity join between two CSV files. 4 | 5 | For each row in the first file, take the specified join column and find 6 | similar rows in the second file based on ngram similarity to a specified 7 | column in the second file. For each resulting pair of rows, output a row 8 | consisting of the fields from the first file, a column with the similarity 9 | value, and then the fields from the second file. 10 | """ 11 | from __future__ import print_function 12 | 13 | import csv, os, re 14 | from ngram import NGram 15 | 16 | def lowstrip(term): 17 | """Convert to lowercase and strip spaces""" 18 | term = re.sub(r'\s+', ' ', term) 19 | term = term.lower() 20 | return term 21 | 22 | def main(left_path, left_column, right_path, right_column, 23 | outfile, titles, join, minscore, count, warp): 24 | """Perform the similarity join""" 25 | right_file = csv.reader(open(right_path, 'r')) 26 | if titles: 27 | right_header = next(right_file) 28 | index = NGram((tuple(r) for r in right_file), 29 | threshold=minscore, 30 | warp=warp, key=lambda x: lowstrip(x[right_column])) 31 | left_file = csv.reader(open(left_path, 'r')) 32 | out = csv.writer(open(outfile, 'w'), lineterminator='\n') 33 | if titles: 34 | left_header = next(left_file) 35 | out.writerow(left_header + ["Rank", "Similarity"] + right_header) 36 | for row in left_file: 37 | if not row: continue # skip blank lines 38 | row = tuple(row) 39 | results = index.search(lowstrip(row[left_column]), threshold=minscore) 40 | if results: 41 | if count > 0: 42 | results = results[:count] 43 | for rank, result in enumerate(results, 1): 44 | out.writerow(row + (rank, result[1]) + result[0]) 45 | elif join == "outer": 46 | out.writerow(row) 47 | 48 | def console_main(): 49 | """Process command-line arguments.""" 50 | from argparse import ArgumentParser 51 | parser = ArgumentParser(description=__doc__) 52 | parser.add_argument('-t', '--titles', action='store_true', 53 | help='input files have column titles') 54 | parser.add_argument( 55 | '-j', '--join', choices=['inner', 'outer'], 56 | help=('The kind of left join to perform. Outer join outputs left-hand ' 57 | 'rows which have no right hand match, while inner join discards ' 58 | 'such rows. Default: %(default)s')) 59 | parser.add_argument('-m', '--minscore', type=float, 60 | help='Minimum match score: %(default)s') 61 | parser.add_argument('-c', '--count', type=int, 62 | help='Max number of rows to match (0 for all): %(default)s') 63 | parser.add_argument('-w', '--warp', type=float, 64 | help='N-gram warp, higher helps short strings: %(default)s') 65 | parser.add_argument('left', nargs=1, help='First CSV file') 66 | parser.add_argument('leftcolumn', nargs=1, type=int, help='Column in first CSV file') 67 | parser.add_argument('right', nargs=1, help='Second CSV file') 68 | parser.add_argument('rightcolumn', nargs=1, type=int, help='Column in second CSV file') 69 | parser.add_argument('outfile', nargs=1, help='Output CSV file') 70 | parser.set_defaults( 71 | titles=False, join='outer', minscore=0.24, count=0, warp=1.0) 72 | args = parser.parse_args() 73 | for path in [args.left[0], args.right[0]]: 74 | if not os.path.isfile(path): 75 | parser.error('File "%s" does not exist.' % path) 76 | if not (0 <= args.minscore <= 1.0): 77 | parser.error("Minimum score must be between 0 and 1") 78 | if not args.count >= 0: 79 | parser.error("Maximum number of matches per row must be non-negative.") 80 | if args.count == 0: 81 | args.count = None # to return all results 82 | main(args.left[0], args.leftcolumn[0], args.right[0], args.rightcolumn[0], 83 | args.outfile[0], args.titles, args.join, args.minscore, args.count, 84 | args.warp) 85 | 86 | 87 | if __name__ == '__main__': 88 | console_main() 89 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = ngram 3 | version = 4.0.3 4 | description = A `set` subclass providing fuzzy search based on N-grams. 5 | long_description = file: README 6 | long_description_content_type = text/x-rst 7 | author = Graham Poulter, Michel Albert 8 | maintainer = Graham Poulter 9 | license = LGPL3 10 | url = https://github.com/gpoulter/python-ngram 11 | download_url = http://pypi.python.org/pypi/ngram 12 | keywords = ngram set string text similarity 13 | platforms = any 14 | project_urls = 15 | Documentation = https://python-ngram.readthedocs.io/en/latest/ 16 | classifiers = 17 | Development Status :: 5 - Production/Stable 18 | Intended Audience :: Developers 19 | License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) 20 | License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) 21 | License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) 22 | Natural Language :: English 23 | Topic :: Text Processing 24 | Topic :: Text Processing :: Indexing 25 | Topic :: Text Processing :: Linguistic 26 | Operating System :: OS Independent 27 | Programming Language :: Python 28 | Programming Language :: Python :: 3 29 | 30 | [build_sphinx] 31 | source-dir = docs 32 | build-dir = docs/build 33 | all_files = 1 34 | 35 | [upload_sphinx] 36 | upload-dir = docs/build/html 37 | 38 | [nosetests] 39 | exe = 1 40 | 41 | [options] 42 | py_modules = 43 | ngram 44 | python_requires = >=3.0 45 | scripts = 46 | scripts/csvjoin.py 47 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | setuptools.setup() -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gpoulter/python-ngram/2896d63f366b8d111fdd1d24e5b24ae25474aa6c/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_csvjoin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import os 4 | import os.path 5 | import subprocess 6 | import sys 7 | import tempfile 8 | import textwrap 9 | import unittest 10 | 11 | class CsvjoinTests(unittest.TestCase): 12 | 13 | def setUp(self): 14 | self.tmpdir = tempfile.mkdtemp(prefix="csvjoin_test_") 15 | self.leftpath = os.path.join(self.tmpdir, 'left') 16 | self.rightpath = os.path.join(self.tmpdir, 'right') 17 | self.outpath = os.path.join(self.tmpdir, 'output') 18 | with open(self.leftpath, 'w') as left: 19 | left.write('''ID,NAME\n1,Joe\n2,Kin\n3,ZAS''') 20 | with open(self.rightpath, 'w') as right: 21 | right.write('''ID,NAME\nID,NAME\nA,Joe\nB,Jon\nC,Job\nD,Kim''') 22 | 23 | def tearDown(self): 24 | os.remove(self.leftpath) 25 | os.remove(self.rightpath) 26 | os.remove(self.outpath) 27 | os.rmdir(self.tmpdir) 28 | 29 | def test_csvjoin(self): 30 | args = [ 31 | sys.executable, 32 | 'scripts/csvjoin.py', '--titles', '-j', 'outer', '--minscore=0.24', 33 | '--count=5', '--warp=1.0', 34 | self.leftpath, '1', self.rightpath, '1', self.outpath 35 | ] 36 | print(args) 37 | subprocess.call(args) 38 | with open(self.outpath, 'r') as out: 39 | result = '\n'.join(s.strip() for s in out.readlines()) 40 | correct = textwrap.dedent("""\ 41 | ID,NAME,Rank,Similarity,ID,NAME 42 | 1,Joe,1,1.0,A,Joe 43 | 1,Joe,2,0.25,B,Jon 44 | 1,Joe,3,0.25,C,Job 45 | 2,Kin,1,0.25,D,Kim 46 | 3,ZAS""") 47 | self.assertEqual(result, correct) 48 | 49 | if __name__ == "__main__": 50 | unittest.main() 51 | -------------------------------------------------------------------------------- /tests/test_ngram.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Unit tests for the ngram module.""" 5 | 6 | import unittest 7 | from ngram import NGram 8 | 9 | 10 | class NgramTests(unittest.TestCase): 11 | """Tests of the ngram class""" 12 | 13 | items = ['sdafaf', 'asfwef', 'asdfawe', 'adfwe', 'askfjwehiuasdfji'] 14 | 15 | def test_ngram_search(self): 16 | """Tests from the original ngram.py, to check that the 17 | rewrite still uses the same underlying algorithm""" 18 | 19 | # Basic searching of the index 20 | idx = NGram(self.items) 21 | self.assertEqual(idx.search('askfjwehiuasdfji'), [ 22 | ('askfjwehiuasdfji', 1.0), 23 | ('asdfawe', 0.17391304347826086), 24 | ('asfwef', 0.083333333333333329), 25 | ('adfwe', 0.041666666666666664)]) 26 | self.assertEqual(idx.search('afadfwe')[:2], 27 | [('adfwe', 0.59999999999999998), 28 | ('asdfawe', 0.20000000000000001)]) 29 | 30 | # Pairwise comparison of strings 31 | self.assertEqual(NGram.compare('sdfeff', 'sdfeff'), 1.0) 32 | self.assertEqual(NGram.compare('sdfeff', 'zzzzzz'), 0.0) 33 | 34 | def test_set_operations(self): 35 | """Test advanced set operations""" 36 | items1 = set(["abcde", "cdefg", "fghijk", "ijklm"]) 37 | items2 = set(["cdefg", "lmnop"]) 38 | idx1 = NGram(items1) 39 | idx2 = NGram(items2) 40 | results = lambda L: sorted(x[0] for x in L) 41 | # Item removal 42 | self.assertEqual(results(idx1.search('cde')), ["abcde", "cdefg"]) 43 | idx1.remove('abcde') 44 | self.assertEqual(results(idx1.search('cde')), ["cdefg"]) 45 | # Set intersection operation 46 | items1.remove('abcde') 47 | idx1.intersection_update(idx2) 48 | self.assertEqual(idx1, items1.intersection(items2)) 49 | self.assertEqual(results(idx1.search('lmn')), []) 50 | self.assertEqual(results(idx1.search('ijk')), []) 51 | self.assertEqual(results(idx1.search('def')), ['cdefg']) 52 | 53 | 54 | if __name__ == "__main__": 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist=py3 3 | 4 | [testenv] 5 | deps= 6 | pytest 7 | sphinx 8 | commands= 9 | py.test \ 10 | --ignore=setup.py \ 11 | --ignore=docs/conf.py \ 12 | --doctest-modules \ 13 | --doctest-glob=*.rst \ 14 | [] 15 | --------------------------------------------------------------------------------