inflect-2.1.0/0000755000076500000240000000000013372337712013530 5ustar jaracostaff00000000000000inflect-2.1.0/.flake80000644000076500000240000000014113372337710014675 0ustar jaracostaff00000000000000[flake8] max-line-length=88 ignore = E203 W504 W503 exclude = .git .tox build dist .eggs inflect-2.1.0/.gitignore0000644000076500000240000000010413274375005015511 0ustar jaracostaff00000000000000*.pyc MANIFEST dist/* cover/* htmlcov/* .tox/* *.egg-info .coverage inflect-2.1.0/.travis.yml0000644000076500000240000000064113372337710015640 0ustar jaracostaff00000000000000language: python sudo: false # Use container-based infrastructure matrix: fast_finish: true include: - python: 3.7 dist: xenial sudo: true - python: 3.6 - python: 3.5 - python: 3.4 - python: pypy3 - python: 2.7 - python: pypy install: - pip install coverage tox-travis script: tox after_success: - pip install coveralls - coveralls after_script: - coverage report inflect-2.1.0/CHANGES.txt0000644000076500000240000000642613372337710015347 0ustar jaracostaff00000000000000ver 2.1.0 * #29: Relicensed under the more permissive MIT License. ver 2.0.1 * #57: Fix pluralization of taco. ver 2.0.0 * #37: fix inconsistencies with the inflect method We now build and parse AST to extract function arguments instead of relying on regular expressions. This also adds support for keyword arguments and built-in constants when calling functions in the string. Unfortunately, this is not backwards compatible in some cases: * Strings should now be wrapped in single or double quotes p.inflect("singular_noun(to them)") should now be p.inflect("singular_noun('to them')") * Empty second argument to a function will now be parsed as None instead of ''. p.inflect("num(%d,) eggs" % 2) now prints "2 eggs" instead of " eggs" Since None, True and False are now supported, they can be passed explicitly: p.inflect("num(%d, False) eggs" % 2) will print " eggs" p.inflect("num(%d, True) eggs" % 2) will print "2 eggs" ver 1.0.2 * #53: Improved unicode handling. * #5 and #40 via #55: Fix capitalization issues in processes where more than one word is involved. * #56: Handle correctly units containing 'degree' and 'per'. ver 1.0.1 * #31: fix extraneous close parentheses. ver 1.0.0 * Dropped support for Python 3.3. ver 0.3.1 * Fixed badges in readme. ver 0.3.0 * Moved hosting to `jazzband `_. ver 0.2.5 * Fixed TypeError while parsing compounds (by yavarhusain) * Fixed encoding issue in setup.py on Python 3 ver 0.2.4 * new maintainer (Alex Grönholm) * added Python 3 compatibility (by Thorben Krüger) ver 0.2.3 * fix a/an for dishonor, Honolulu, mpeg, onetime, Ugandan, Ukranian, Unabomber, unanimous, US * merge in 'subspecies' fix by UltraNurd * add arboretum to classical plurals * prevent crash with singular_noun('ys') ver 0.2.2 * change numwords to number_to_words in strings * improve some docstrings * comment out imports for unused .inflectrc * remove unused exception class ver 0.2.1 * remove incorrect gnome_sudoku import ver 0.2.0 * add gender() to select the gender of singular pronouns * replace short named methods with longer methods. shorted method now print a message and rasie DecrecationWarning pl -> plural plnoun -> plural_noun plverb -> plural_verb pladj -> plural_adjective sinoun -> singular_noun prespart -> present_participle numwords -> number_to_words plequal -> compare plnounequal -> compare_nouns plverbequal -> compare_verbs pladjequal -> compare_adjs wordlist -> join * change classical() to only accept keyword args: only one way to do it * fix bug in numwords where hundreds was giving the wrong number when group=3 ver 0.1.8 (2010-07-10) * add line to setup showing that this provides 'inflect' so that inflect_dj can require it * add the rest of the tests from the Perl version ver 0.1.7 (2010-07-09) * replace most of the regular expressions in _plnoun and _sinoun. They run several times faster now. ver 0.1.6 (2010-07-03) * add method sinoun() to generate the singular of a plural noun. Phew! * add changes from new Perl version: 1.892 * start adding tests from Perl version * add test to check sinoun(plnoun(word)) == word Can now use word lists to check these methods without needing to have a list of plurals. ;-) * fix die -> dice inflect-2.1.0/CONTRIBUTING.md0000644000076500000240000000046413274377101015762 0ustar jaracostaff00000000000000[![Jazzband](https://jazzband.co/static/img/jazzband.svg)](https://jazzband.co/) This is a [Jazzband](https://jazzband.co/) project. By contributing you agree to abide by the [Contributor Code of Conduct](https://jazzband.co/about/conduct) and follow the [guidelines](https://jazzband.co/about/guidelines). inflect-2.1.0/LICENSE0000644000076500000240000000203213372337710014530 0ustar jaracostaff00000000000000Copyright Jason R. Coombs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. inflect-2.1.0/PKG-INFO0000644000076500000240000016654713372337712014650 0ustar jaracostaff00000000000000Metadata-Version: 1.2 Name: inflect Version: 2.1.0 Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words Home-page: https://github.com/jazzband/inflect Author: Paul Dyson Author-email: pwdyson@yahoo.com Maintainer: Alex Gronholm Maintainer-email: alex.gronholm@nextday.fi License: UNKNOWN Description: ========== inflect.py ========== .. image:: https://travis-ci.org/jazzband/inflect.svg?branch=master :target: https://travis-ci.org/jazzband/inflect .. image:: https://coveralls.io/repos/github/jazzband/inflect/badge.svg?branch=master :target: https://coveralls.io/github/jazzband/inflect?branch=master .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband This is a `Jazzband `_ project. By contributing you agree to abide by the `Contributor Code of Conduct `_ and follow the `guidelines `_. NAME ==== inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words. INSTALLATION ============ ``pip install inflect`` SYNOPSIS ======== :: import inflect p = inflect.engine() # METHODS: # plural plural_noun plural_verb plural_adj singular_noun no num # compare compare_nouns compare_nouns compare_adjs # a an # present_participle # ordinal number_to_words # join # inflect classical gender # defnoun defverb defadj defa defan # UNCONDITIONALLY FORM THE PLURAL print("The plural of ", word, " is ", p.plural(word)) # CONDITIONALLY FORM THE PLURAL print("I saw", cat_count, p.plural("cat",cat_count)) # FORM PLURALS FOR SPECIFIC PARTS OF SPEECH print(p.plural_noun("I",N1), p.plural_verb("saw",N1), p.plural_adj("my",N2), \) p.plural_noun("saw",N2) # FORM THE SINGULAR OF PLURAL NOUNS print("The singular of ", word, " is ", p.singular_noun(word)) # SELECT THE GENDER OF SINGULAR PRONOUNS print(p.singular_noun('they') # 'it') p.gender('f') print(p.singular_noun('they') # 'she') # DEAL WITH "0/1/N" -> "no/1/N" TRANSLATION: print("There ", p.plural_verb("was",errors), p.no(" error",errors)) # USE DEFAULT COUNTS: print(p.num(N1,""), p.plural("I"), p.plural_verb(" saw"), p.num(N2), p.plural_noun(" saw")) print("There ", p.num(errors,''), p.plural_verb("was"), p.no(" error")) # COMPARE TWO WORDS "NUMBER-INSENSITIVELY": print("same\n" if p.compare(word1, word2)) print("same noun\n" if p.compare_nouns(word1, word2)) print("same verb\n" if p.compare_verbs(word1, word2)) print("same adj.\n" if p.compare_adjs(word1, word2)) # ADD CORRECT "a" OR "an" FOR A GIVEN WORD: print("Did you want ", p.a(thing), " or ", p.an(idea)) # CONVERT NUMERALS INTO ORDINALS (i.e. 1->1st, 2->2nd, 3->3rd, etc.) print("It was", p.ordinal(position), " from the left\n") # CONVERT NUMERALS TO WORDS (i.e. 1->"one", 101->"one hundred and one", etc.) # RETURNS A SINGLE STRING... words = p.number_to_words(1234) # "one thousand, two hundred and thirty-four" words = p.number_to_words(p.ordinal(1234)) # "one thousand, two hundred and thirty-fourth" # GET BACK A LIST OF STRINGS, ONE FOR EACH "CHUNK"... words = p.number_to_words(1234, getlist=True) # ("one thousand","two hundred and thirty-four") # OPTIONAL PARAMETERS CHANGE TRANSLATION: words = p.number_to_words(12345, group=1) # "one, two, three, four, five" words = p.number_to_words(12345, group=2) # "twelve, thirty-four, five" words = p.number_to_words(12345, group=3) # "one twenty-three, forty-five" words = p.number_to_words(1234, andword='') # "one thousand, two hundred thirty-four" words = p.number_to_words(1234, andword=', plus') # "one thousand, two hundred, plus thirty-four" #TODO: I get no comma before plus: check perl words = p.number_to_words(555_1202, group=1, zero='oh') # "five, five, five, one, two, oh, two" words = p.number_to_words(555_1202, group=1, one='unity') # "five, five, five, unity, two, oh, two" words = p.number_to_words(123.456, group=1, decimal='mark') # "one two three mark four five six" #TODO: DOCBUG: perl gives commas here as do I # LITERAL STYLE ONLY NAMES NUMBERS LESS THAN A CERTAIN THRESHOLD... words = p.number_to_words( 9, threshold=10); # "nine" words = p.number_to_words( 10, threshold=10); # "ten" words = p.number_to_words( 11, threshold=10); # "11" words = p.number_to_words(1000, threshold=10); # "1,000" # JOIN WORDS INTO A LIST: mylist = join(("apple", "banana", "carrot")) # "apple, banana, and carrot" mylist = join(("apple", "banana")) # "apple and banana" mylist = join(("apple", "banana", "carrot"), final_sep="") # "apple, banana and carrot" # REQUIRE "CLASSICAL" PLURALS (EG: "focus"->"foci", "cherub"->"cherubim") p.classical() # USE ALL CLASSICAL PLURALS p.classical(all=True) # USE ALL CLASSICAL PLURALS p.classical(all=False) # SWITCH OFF CLASSICAL MODE p.classical(zero=True) # "no error" INSTEAD OF "no errors" p.classical(zero=False) # "no errors" INSTEAD OF "no error" p.classical(herd=True) # "2 buffalo" INSTEAD OF "2 buffalos" p.classical(herd=False) # "2 buffalos" INSTEAD OF "2 buffalo" p.classical(persons=True) # "2 chairpersons" INSTEAD OF "2 chairpeople" p.classical(persons=False) # "2 chairpeople" INSTEAD OF "2 chairpersons" p.classical(ancient=True) # "2 formulae" INSTEAD OF "2 formulas" p.classical(ancient=False) # "2 formulas" INSTEAD OF "2 formulae" # INTERPOLATE "plural()", "plural_noun()", "plural_verb()", "plural_adj()", "singular_noun()", # a()", "an()", "num()" AND "ordinal()" WITHIN STRINGS: print(p.inflect("The plural of {0} is plural({0})".format(word))) print(p.inflect("The singular of {0} is singular_noun({0})".format(word))) print(p.inflect("I saw {0} plural("cat",{0})".format(cat_count))) print(p.inflect("plural(I,{0}) plural_verb(saw,{0}) plural(a,{1}) plural_noun(saw,{1})".format(N1, N2))) print(p.inflect("num({0},)plural(I) plural_verb(saw) num({1},)plural(a) plural_noun(saw)".format(N1, N2))) print(p.inflect("I saw num({0}) plural("cat")\nnum()".format(cat_count))) print(p.inflect("There plural_verb(was,{0}) no(error,{0})".format(errors))) print(p.inflect("There num({0},) plural_verb(was) no(error)".format(errors))) print(p.inflect("Did you want a({0}) or an({1})".format(thing, idea))) print(p.inflect("It was ordinal({0}) from the left".format(position))) # ADD USER-DEFINED INFLECTIONS (OVERRIDING INBUILT RULES): p.defnoun( "VAX", "VAXen" ) # SINGULAR => PLURAL p.defverb( "will" , "shall", # 1ST PERSON SINGULAR => PLURAL "will" , "will", # 2ND PERSON SINGULAR => PLURAL "will" , "will") # 3RD PERSON SINGULAR => PLURAL p.defadj( "hir" , "their") # SINGULAR => PLURAL p.defa("h") # "AY HALWAYS SEZ 'HAITCH'!" p.defan( "horrendous.*" ) # "AN HORRENDOUS AFFECTATION" DESCRIPTION =========== The methods of the class ``engine`` in module ``inflect.py`` provide plural inflections, singular noun inflections, "a"/"an" selection for English words, and manipulation of numbers as words. Plural forms of all nouns, most verbs, and some adjectives are provided. Where appropriate, "classical" variants (for example: "brother" -> "brethren", "dogma" -> "dogmata", etc.) are also provided. Single forms of nouns are also provided. The gender of singular pronouns can be chosen (for example "they" -> "it" or "she" or "he" or "they"). Pronunciation-based "a"/"an" selection is provided for all English words, and most initialisms. It is also possible to inflect numerals (1,2,3) to ordinals (1st, 2nd, 3rd) and to English words ("one", "two", "three"). In generating these inflections, ``inflect.py`` follows the Oxford English Dictionary and the guidelines in Fowler's Modern English Usage, preferring the former where the two disagree. The module is built around standard British spelling, but is designed to cope with common American variants as well. Slang, jargon, and other English dialects are *not* explicitly catered for. Where two or more inflected forms exist for a single word (typically a "classical" form and a "modern" form), ``inflect.py`` prefers the more common form (typically the "modern" one), unless "classical" processing has been specified (see `MODERN VS CLASSICAL INFLECTIONS`). FORMING PLURALS AND SINGULARS ============================= Inflecting Plurals and Singulars -------------------------------- All of the ``plural...`` plural inflection methods take the word to be inflected as their first argument and return the corresponding inflection. Note that all such methods expect the *singular* form of the word. The results of passing a plural form are undefined (and unlikely to be correct). Similarly, the ``si...`` singular inflection method expects the *plural* form of the word. The ``plural...`` methods also take an optional second argument, which indicates the grammatical "number" of the word (or of another word with which the word being inflected must agree). If the "number" argument is supplied and is not ``1`` (or ``"one"`` or ``"a"``, or some other adjective that implies the singular), the plural form of the word is returned. If the "number" argument *does* indicate singularity, the (uninflected) word itself is returned. If the number argument is omitted, the plural form is returned unconditionally. The ``si...`` method takes a second argument in a similar fashion. If it is some form of the number ``1``, or is omitted, the singular form is returned. Otherwise the plural is returned unaltered. The various methods of ``inflect.engine`` are: ``plural_noun(word, count=None)`` The method ``plural_noun()`` takes a *singular* English noun or pronoun and returns its plural. Pronouns in the nominative ("I" -> "we") and accusative ("me" -> "us") cases are handled, as are possessive pronouns ("mine" -> "ours"). ``plural_verb(word, count=None)`` The method ``plural_verb()`` takes the *singular* form of a conjugated verb (that is, one which is already in the correct "person" and "mood") and returns the corresponding plural conjugation. ``plural_adj(word, count=None)`` The method ``plural_adj()`` takes the *singular* form of certain types of adjectives and returns the corresponding plural form. Adjectives that are correctly handled include: "numerical" adjectives ("a" -> "some"), demonstrative adjectives ("this" -> "these", "that" -> "those"), and possessives ("my" -> "our", "cat's" -> "cats'", "child's" -> "childrens'", etc.) ``plural(word, count=None)`` The method ``plural()`` takes a *singular* English noun, pronoun, verb, or adjective and returns its plural form. Where a word has more than one inflection depending on its part of speech (for example, the noun "thought" inflects to "thoughts", the verb "thought" to "thought"), the (singular) noun sense is preferred to the (singular) verb sense. Hence ``plural("knife")`` will return "knives" ("knife" having been treated as a singular noun), whereas ``plural("knifes")`` will return "knife" ("knifes" having been treated as a 3rd person singular verb). The inherent ambiguity of such cases suggests that, where the part of speech is known, ``plural_noun``, ``plural_verb``, and ``plural_adj`` should be used in preference to ``plural``. ``singular_noun(word, count=None)`` The method ``singular_noun()`` takes a *plural* English noun or pronoun and returns its singular. Pronouns in the nominative ("we" -> "I") and accusative ("us" -> "me") cases are handled, as are possessive pronouns ("ours" -> "mine"). When third person singular pronouns are returned they take the neuter gender by default ("they" -> "it"), not ("they"-> "she") nor ("they" -> "he"). This can be changed with ``gender()``. Note that all these methods ignore any whitespace surrounding the word being inflected, but preserve that whitespace when the result is returned. For example, ``plural(" cat ")`` returns " cats ". ``gender(genderletter)`` The third person plural pronoun takes the same form for the female, male and neuter (e.g. "they"). The singular however, depends upon gender (e.g. "she", "he", "it" and "they" -- "they" being the gender neutral form.) By default ``singular_noun`` returns the neuter form, however, the gender can be selected with the ``gender`` method. Pass the first letter of the gender to ``gender`` to return the f(eminine), m(asculine), n(euter) or t(hey) form of the singular. e.g. gender('f') followed by singular_noun('themselves') returns 'herself'. Numbered plurals ---------------- The ``plural...`` methods return only the inflected word, not the count that was used to inflect it. Thus, in order to produce "I saw 3 ducks", it is necessary to use:: print("I saw", N, p.plural_noun(animal,N)) Since the usual purpose of producing a plural is to make it agree with a preceding count, inflect.py provides a method (``no(word, count)``) which, given a word and a(n optional) count, returns the count followed by the correctly inflected word. Hence the previous example can be rewritten:: print("I saw ", p.no(animal,N)) In addition, if the count is zero (or some other term which implies zero, such as ``"zero"``, ``"nil"``, etc.) the count is replaced by the word "no". Hence, if ``N`` had the value zero, the previous example would print(the somewhat more elegant::) I saw no animals rather than:: I saw 0 animals Note that the name of the method is a pun: the method returns either a number (a *No.*) or a ``"no"``, in front of the inflected word. Reducing the number of counts required -------------------------------------- In some contexts, the need to supply an explicit count to the various ``plural...`` methods makes for tiresome repetition. For example:: print(plural_adj("This",errors), plural_noun(" error",errors), \) plural_verb(" was",errors), " fatal." inflect.py therefore provides a method (``num(count=None, show=None)``) which may be used to set a persistent "default number" value. If such a value is set, it is subsequently used whenever an optional second "number" argument is omitted. The default value thus set can subsequently be removed by calling ``num()`` with no arguments. Hence we could rewrite the previous example:: p.num(errors) print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") p.num() Normally, ``num()`` returns its first argument, so that it may also be "inlined" in contexts like:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") However, in certain contexts (see `INTERPOLATING INFLECTIONS IN STRINGS`) it is preferable that ``num()`` return an empty string. Hence ``num()`` provides an optional second argument. If that argument is supplied (that is, if it is defined) and evaluates to false, ``num`` returns an empty string instead of its first argument. For example:: print(p.num(errors,0), p.no("error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Number-insensitive equality --------------------------- inflect.py also provides a solution to the problem of comparing words of differing plurality through the methods ``compare(word1, word2)``, ``compare_nouns(word1, word2)``, ``compare_verbs(word1, word2)``, and ``compare_adjs(word1, word2)``. Each of these methods takes two strings, and compares them using the corresponding plural-inflection method (``plural()``, ``plural_noun()``, ``plural_verb()``, and ``plural_adj()`` respectively). The comparison returns true if: - the strings are equal, or - one string is equal to a plural form of the other, or - the strings are two different plural forms of the one word. Hence all of the following return true:: p.compare("index","index") # RETURNS "eq" p.compare("index","indexes") # RETURNS "s:p" p.compare("index","indices") # RETURNS "s:p" p.compare("indexes","index") # RETURNS "p:s" p.compare("indices","index") # RETURNS "p:s" p.compare("indices","indexes") # RETURNS "p:p" p.compare("indexes","indices") # RETURNS "p:p" p.compare("indices","indices") # RETURNS "eq" As indicated by the comments in the previous example, the actual value returned by the various ``compare`` methods encodes which of the three equality rules succeeded: "eq" is returned if the strings were identical, "s:p" if the strings were singular and plural respectively, "p:s" for plural and singular, and "p:p" for two distinct plurals. Inequality is indicated by returning an empty string. It should be noted that two distinct singular words which happen to take the same plural form are *not* considered equal, nor are cases where one (singular) word's plural is the other (plural) word's singular. Hence all of the following return false:: p.compare("base","basis") # ALTHOUGH BOTH -> "bases" p.compare("syrinx","syringe") # ALTHOUGH BOTH -> "syringes" p.compare("she","he") # ALTHOUGH BOTH -> "they" p.compare("opus","operas") # ALTHOUGH "opus" -> "opera" -> "operas" p.compare("taxi","taxes") # ALTHOUGH "taxi" -> "taxis" -> "taxes" Note too that, although the comparison is "number-insensitive" it is *not* case-insensitive (that is, ``plural("time","Times")`` returns false. To obtain both number and case insensitivity, use the ``lower()`` method on both strings (that is, ``plural("time".lower(), "Times".lower())`` returns true). OTHER VERB FORMS ================ Present participles ------------------- ``inflect.py`` also provides the ``present_participle`` method, which can take a 3rd person singular verb and correctly inflect it to its present participle:: p.present_participle("runs") # "running" p.present_participle("loves") # "loving" p.present_participle("eats") # "eating" p.present_participle("bats") # "batting" p.present_participle("spies") # "spying" PROVIDING INDEFINITE ARTICLES ============================= Selecting indefinite articles ----------------------------- inflect.py provides two methods (``a(word, count=None)`` and ``an(word, count=None)``) which will correctly prepend the appropriate indefinite article to a word, depending on its pronunciation. For example:: p.a("cat") # -> "a cat" p.an("cat") # -> "a cat" p.a("euphemism") # -> "a euphemism" p.a("Euler number") # -> "an Euler number" p.a("hour") # -> "an hour" p.a("houri") # -> "a houri" The two methods are *identical* in function and may be used interchangeably. The only reason that two versions are provided is to enhance the readability of code such as:: print("That is ", an(errortype), " error) print("That is ", a(fataltype), " fatal error) Note that in both cases the actual article provided depends *only* on the pronunciation of the first argument, *not* on the name of the method. ``a()`` and ``an()`` will ignore any indefinite article that already exists at the start of the string. Thus:: half_arked = [ "a elephant", "a giraffe", "an ewe", "a orangutan", ] for txt in half_arked: print(p.a(txt)) # prints: # an elephant # a giraffe # a ewe # an orangutan ``a()`` and ``an()`` both take an optional second argument. As with the ``plural...`` methods, this second argument is a "number" specifier. If its value is ``1`` (or some other value implying singularity), ``a()`` and ``an()`` insert "a" or "an" as appropriate. If the number specifier implies plurality, (``a()`` and ``an()`` insert the actual second argument instead. For example:: p.a("cat",1) # -> "a cat" p.a("cat",2) # -> "2 cat" p.a("cat","one") # -> "one cat" p.a("cat","no") # -> "no cat" Note that, as implied by the previous examples, ``a()`` and ``an()`` both assume that their job is merely to provide the correct qualifier for a word (that is: "a", "an", or the specified count). In other words, they assume that the word they are given has already been correctly inflected for plurality. Hence, if ``N`` has the value 2, then:: print(p.a("cat",N)) prints "2 cat", instead of "2 cats". The correct approach is to use:: print(p.a(p.plural("cat",N),N)) or, better still:: print(p.no("cat",N)) Note too that, like the various ``plural...`` methods, whenever ``a()`` and ``an()`` are called with only one argument they are subject to the effects of any preceding call to ``num()``. Hence, another possible solution is:: p.num(N) print(p.a(p.plural("cat"))) Indefinite articles and initialisms ----------------------------------- "Initialisms" (sometimes inaccurately called "acronyms") are terms which have been formed from the initial letters of words in a phrase (for example, "NATO", "NBL", "S.O.S.", "SCUBA", etc.) Such terms present a particular challenge when selecting between "a" and "an", since they are sometimes pronounced as if they were a single word ("nay-tow", "sku-ba") and sometimes as a series of letter names ("en-eff-ell", "ess-oh-ess"). ``a()`` and ``an()`` cope with this dichotomy using a series of inbuilt rules, which may be summarized as: If the word starts with a single letter, followed by a period or dash (for example, "R.I.P.", "C.O.D.", "e-mail", "X-ray", "T-square"), then choose the appropriate article for the *sound* of the first letter ("an R.I.P.", "a C.O.D.", "an e-mail", "an X-ray", "a T-square"). If the first two letters of the word are capitals, consonants, and do not appear at the start of any known English word, (for example, "LCD", "XML", "YWCA"), then once again choose "a" or "an" depending on the *sound* of the first letter ("an LCD", "an XML", "a YWCA"). Otherwise, assume the string is a capitalized word or a pronounceable initialism (for example, "LED", "OPEC", "FAQ", "UNESCO"), and therefore takes "a" or "an" according to the (apparent) pronunciation of the entire word ("a LED", "an OPEC", "a FAQ", "a UNESCO"). Note that rules 1 and 3 together imply that the presence or absence of punctuation may change the selection of indefinite article for a particular initialism (for example, "a FAQ" but "an F.A.Q."). Indefinite articles and "soft H's" ---------------------------------- Words beginning in the letter 'H' present another type of difficulty when selecting a suitable indefinite article. In a few such words (for example, "hour", "honour", "heir") the 'H' is not voiced at all, and so such words inflect with "an". The remaining cases ("voiced H's") may be divided into two categories: "hard H's" (such as "hangman", "holograph", "hat", etc.) and "soft H's" (such as "hysterical", "horrendous", "holy", etc.) Hard H's always take "a" as their indefinite article, and soft H's normally do so as well. But *some* English speakers prefer "an" for soft H's (although the practice is now generally considered an affectation, rather than a legitimate grammatical alternative). At present, the ``a()`` and ``an()`` methods ignore soft H's and use "a" for any voiced 'H'. The author would, however, welcome feedback on this decision (envisaging a possible future "soft H" mode). INFLECTING ORDINALS =================== Occasionally it is useful to present an integer value as an ordinal rather than as a numeral. For example:: Enter password (1st attempt): ******** Enter password (2nd attempt): ********* Enter password (3rd attempt): ********* No 4th attempt. Access denied. To this end, inflect.py provides the ``ordinal()`` method. ``ordinal()`` takes a single argument and forms its ordinal equivalent. If the argument isn't a numerical integer, it just adds "-th". CONVERTING NUMBERS TO WORDS =========================== The method ``number_to_words`` takes a number (cardinal or ordinal) and returns an English representation of that number. :: word = p.number_to_words(1234567) puts the string:: "one million, two hundred and thirty-four thousand, five hundred and sixty-seven" into ``words``. A list can be return where each comma-separated chunk is returned as a separate element. Hence:: words = p.number_to_words(1234567, wantlist=True) puts the list:: ["one million", "two hundred and thirty-four thousand", "five hundred and sixty-seven"] into ``words``. Non-digits (apart from an optional leading plus or minus sign, any decimal points, and ordinal suffixes -- see below) are silently ignored, so the following all produce identical results:: p.number_to_words(5551202) p.number_to_words(5_551_202) p.number_to_words("5,551,202") p.number_to_words("555-1202") That last case is a little awkward since it's almost certainly a phone number, and "five million, five hundred and fifty-one thousand, two hundred and two" probably isn't what's wanted. To overcome this, ``number_to_words()`` takes an optional argument, 'group', which changes how numbers are translated. The argument must be a positive integer less than four, which indicated how the digits of the number are to be grouped. If the argument is ``1``, then each digit is translated separately. If the argument is ``2``, pairs of digits (starting from the *left*) are grouped together. If the argument is ``3``, triples of numbers (again, from the *left*) are grouped. Hence:: p.number_to_words("555-1202", group=1) returns ``"five, five, five, one, two, zero, two"``, whilst:: p.number_to_words("555-1202", group=2) returns ``"fifty-five, fifty-one, twenty, two"``, and:: p.number_to_words("555-1202", group=3) returns ``"five fifty-five, one twenty, two"``. Phone numbers are often written in words as ``"five..five..five..one..two..zero..two"``, which is also easy to achieve:: join '..', p.number_to_words("555-1202", group=>1) ``number_to_words`` also handles decimal fractions. Hence:: p.number_to_words("1.2345") returns ``"one point two three four five"`` in a scalar context and ``("one","point","two","three","four","five")``) in an array context. Exponent form (``"1.234e56"``) is not yet handled. Multiple decimal points are only translated in one of the "grouping" modes. Hence:: p.number_to_words(101.202.303) returns ``"one hundred and one point two zero two three zero three"``, whereas:: p.number_to_words(101.202.303, group=1) returns ``"one zero one point two zero two point three zero three"``. The digit ``'0'`` is unusual in that in may be translated to English as "zero", "oh", or "nought". To cater for this diversity, ``number_to_words`` may be passed a named argument, 'zero', which may be set to the desired translation of ``'0'``. For example:: print(join "..", p.number_to_words("555-1202", group=3, zero='oh')) prints ``"five..five..five..one..two..oh..two"``. By default, zero is rendered as "zero". Likewise, the digit ``'1'`` may be rendered as "one" or "a/an" (or very occasionally other variants), depending on the context. So there is a ``'one'`` argument as well:: for num in [3,2,1,0]: print(p.number_to_words(num, one='a solitary', zero='no more'),) p.plural(" bottle of beer on the wall", num) # prints: # three bottles of beer on the wall # two bottles of beer on the wall # a solitary bottle of beer on the wall # no more bottles of beer on the wall Care is needed if the word "a/an" is to be used as a ``'one'`` value. Unless the next word is known in advance, it's almost always necessary to use the ``A`` function as well:: for word in ["cat aardvark ewe hour".split()]: print(p.a("{0} {1}".format(p.number_to_words(1, one='a'), word))) # prints: # a cat # an aardvark # a ewe # an hour Another major regional variation in number translation is the use of "and" in certain contexts. The named argument 'and' allows the programmer to specify how "and" should be handled. Hence:: print(scalar p.number_to_words("765", andword='')) prints "seven hundred sixty-five", instead of "seven hundred and sixty-five". By default, the "and" is included. The translation of the decimal point is also subject to variation (with "point", "dot", and "decimal" being the favorites). The named argument 'decimal' allows the programmer to how the decimal point should be rendered. Hence:: print(scalar p.number_to_words("666.124.64.101", group=3, decimal='dot')) prints "six sixty-six, dot, one twenty-four, dot, sixty-four, dot, one zero one" By default, the decimal point is rendered as "point". ``number_to_words`` also handles the ordinal forms of numbers. So:: print(p.number_to_words('1st')) print(p.number_to_words('3rd')) print(p.number_to_words('202nd')) print(p.number_to_words('1000000th')) prints:: first third two hundred and twenty-second one millionth Two common idioms in this regard are:: print(p.number_to_words(ordinal(number))) and:: print(p.ordinal(p.number_to_words(number))) These are identical in effect, except when ``number`` contains a decimal:: number = 99.09 print(p.number_to_words(p.ordinal(number)); # ninety-ninth point zero nine) print(p.ordinal(p.number_to_words(number)); # ninety-nine point zero ninth) Use whichever you feel is most appropriate. CONVERTING LISTS OF WORDS TO PHRASES ==================================== When creating a list of words, commas are used between adjacent items, except if the items contain commas, in which case semicolons are used. But if there are less than two items, the commas/semicolons are omitted entirely. The final item also has a conjunction (usually "and" or "or") before it. And although it's technically incorrect (and sometimes misleading), some people prefer to omit the comma before that final conjunction, even when there are more than two items. That's complicated enough to warrant its own method: ``join()``. This method expects a tuple of words, possibly with one or more options. It returns a string that joins the list together in the normal English usage. For example:: print("You chose ", p.join(selected_items)) # You chose barley soup, roast beef, and Yorkshire pudding print("You chose ", p.join(selected_items, final_sep=>"")) # You chose barley soup, roast beef and Yorkshire pudding print("Please chose ", p.join(side_orders, conj=>"or")) # Please chose salad, vegetables, or ice-cream The available options are:: Option named Specifies Default value conj Final conjunction "and" sep Inter-item separator "," last_sep Final separator value of 'sep' option sep_spaced Space follows sep True conj_spaced Spaces around conj True INTERPOLATING INFLECTIONS IN STRINGS ==================================== By far the commonest use of the inflection methods is to produce message strings for various purposes. For example:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Unfortunately the need to separate each method call detracts significantly from the readability of the resulting code. To ameliorate this problem, inflect.py provides a string-interpolating method (``inflect(txt)``), which recognizes calls to the various inflection methods within a string and interpolates them appropriately. Using ``inflect`` the previous example could be rewritten:: print(p.inflect("num({0}) plural_noun(error) plural_verb(was) detected.".format(errors))) if severity > 1: print(p.inflect("plural_adj(This) plural_noun(error) plural_verb(was) fatal.")) Note that ``inflect`` also correctly handles calls to the ``num()`` method (whether interpolated or antecedent). The ``inflect()`` method has a related extra feature, in that it *automatically* cancels any "default number" value before it returns its interpolated string. This means that calls to ``num()`` which are embedded in an ``inflect()``-interpolated string do not "escape" and interfere with subsequent inflections. MODERN VS CLASSICAL INFLECTIONS =============================== Certain words, mainly of Latin or Ancient Greek origin, can form plurals either using the standard English "-s" suffix, or with their original Latin or Greek inflections. For example:: p.plural("stigma") # -> "stigmas" or "stigmata" p.plural("torus") # -> "toruses" or "tori" p.plural("index") # -> "indexes" or "indices" p.plural("millennium") # -> "millenniums" or "millennia" p.plural("ganglion") # -> "ganglions" or "ganglia" p.plural("octopus") # -> "octopuses" or "octopodes" inflect.py caters to such words by providing an "alternate state" of inflection known as "classical mode". By default, words are inflected using their contemporary English plurals, but if classical mode is invoked, the more traditional plural forms are returned instead. The method ``classical()`` controls this feature. If ``classical()`` is called with no arguments, it unconditionally invokes classical mode. If it is called with a single argument, it turns all classical inflects on or off (depending on whether the argument is true or false). If called with two or more arguments, those arguments specify which aspects of classical behaviour are to be used. Thus:: p.classical() # SWITCH ON CLASSICAL MODE print(p.plural("formula") # -> "formulae") p.classical(all=False) # SWITCH OFF CLASSICAL MODE print(p.plural("formula") # -> "formulas") p.classical(cmode=True) # CLASSICAL MODE IFF cmode print(p.plural("formula") # -> "formulae" (IF cmode)) # -> "formulas" (OTHERWISE) p.classical(herd=True) # SWITCH ON CLASSICAL MODE FOR "HERD" NOUNS print(p.plural("wilderbeest") # -> "wilderbeest") p.classical(names=True) # SWITCH ON CLASSICAL MODE FOR NAMES print(p.plural("sally") # -> "sallies") print(p.plural("Sally") # -> "Sallys") Note however that ``classical()`` has no effect on the inflection of words which are now fully assimilated. Hence:: p.plural("forum") # ALWAYS -> "forums" p.plural("criterion") # ALWAYS -> "criteria" LEI assumes that a capitalized word is a person's name. So it forms the plural according to the rules for names (which is that you don't inflect, you just add -s or -es). You can choose to turn that behaviour off (it's on by the default, even when the module isn't in classical mode) by calling `` classical(names=0) `` USER-DEFINED INFLECTIONS ======================== Adding plurals at run-time -------------------------- inflect.py provides five methods which allow the programmer to override the module's behaviour for specific cases: ``defnoun(singular, plural)`` The ``defnoun`` method takes a pair of string arguments: the singular and the plural forms of the noun being specified. The singular form specifies a pattern to be interpolated (as ``m/^(?:$first_arg)$/i``). Any noun matching this pattern is then replaced by the string in the second argument. The second argument specifies a string which is interpolated after the match succeeds, and is then used as the plural form. For example:: defnoun( 'cow' , 'kine') defnoun( '(.+i)o' , '$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!') Note that both arguments should usually be specified in single quotes, so that they are not interpolated when they are specified, but later (when words are compared to them). As indicated by the last example, care also needs to be taken with certain characters in the second argument, to ensure that they are not unintentionally interpolated during comparison. The second argument string may also specify a second variant of the plural form, to be used when "classical" plurals have been requested. The beginning of the second variant is marked by a '|' character:: defnoun( 'cow' , 'cows|kine') defnoun( '(.+i)o' , '$1os|$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!|varmints') If no classical variant is given, the specified plural form is used in both normal and "classical" modes. .. #TODO: check that the following paragraph is implemented If the second argument is ``None`` instead of a string, then the current user definition for the first argument is removed, and the standard plural inflection(s) restored. Note that in all cases, later plural definitions for a particular singular form replace earlier definitions of the same form. For example:: # FIRST, HIDE THE MODERN FORM.... defnoun( 'aviatrix' , 'aviatrices') # LATER, HIDE THE CLASSICAL FORM... defnoun( 'aviatrix' , 'aviatrixes') # FINALLY, RESTORE THE DEFAULT BEHAVIOUR... defnoun( 'aviatrix' , undef) Special care is also required when defining general patterns and associated specific exceptions: put the more specific cases *after* the general pattern. For example:: defnoun( '(.+)us' , '$1i') # EVERY "-us" TO "-i" defnoun( 'bus' , 'buses') # EXCEPT FOR "bus" This "try-most-recently-defined-first" approach to matching user-defined words is also used by ``defverb``, ``defa`` and ``defan``. ``defverb(s1, p1, s2, p2, s3, p3)`` The ``defverb`` method takes three pairs of string arguments (that is, six arguments in total), specifying the singular and plural forms of the three "persons" of verb. As with ``defnoun``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defverb('am' , 'are', 'are' , 'are|art", 'is' , 'are') defverb('have' , 'have', 'have' , 'have", 'ha(s|th)' , 'have') Note that as with ``defnoun``, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defadj(singular, plural)`` The ``defadj`` method takes a pair of string arguments, which specify the singular and plural forms of the adjective being defined. As with ``defnoun`` and ``defadj``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defadj( 'this' , 'these') defadj( 'red' , 'red|gules') As previously, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defa(pattern)`` and ``defan(pattern)`` The ``defa`` and ``defan`` methods each take a single argument, which specifies a pattern. If a word passed to ``a()`` or ``an()`` matches this pattern, it will be prefixed (unconditionally) with the corresponding indefinite article. For example:: defa( 'error') defa( 'in.+') defan('mistake') defan('error') As with the other ``def_...`` methods, such redefinitions are sequential in effect so that, after the above example, "error" will be inflected with "an". The ``<$HOME/.inflectrc`` file ------------------------------ THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET When it is imported, inflect.py executes (as Perl code) the contents of any file named ``.inflectrc`` which it finds in the in the directory where ``Lingua/EN/Inflect.pm`` is installed, or in the current home directory (``$ENV{HOME}``), or in both. Note that the code is executed within the inflect.py namespace. Hence the user or the local Perl guru can make appropriate calls to ``defnoun``, ``defverb``, etc. in one of these ``.inflectrc`` files, to permanently and universally modify the behaviour of the module. For example > cat /usr/local/lib/perl5/Text/Inflect/.inflectrc defnoun "UNIX" => "UN*X|UNICES" defverb "teco" => "teco", # LITERALLY: "to edit with TECO" "teco" => "teco", "tecos" => "teco" defa "Euler.*"; # "Yewler" TURNS IN HIS GRAVE Note that calls to the ``def_...`` methods from within a program will take precedence over the contents of the home directory F<.inflectrc> file, which in turn takes precedence over the system-wide F<.inflectrc> file. DIAGNOSTICS =========== THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET On loading, if the Perl code in a ``.inflectrc`` file is invalid (syntactically or otherwise), an appropriate fatal error is issued. A common problem is not ending the file with something that evaluates to true (as the five ``def_...`` methods do). Using the five ``def_...`` methods directly in a program may also result in fatal diagnostics, if a (singular) pattern or an interpolated (plural) string is somehow invalid. Specific diagnostics related to user-defined inflections are: ``"Bad user-defined singular pattern:\t %s"`` The singular form of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb``, ``defadj``, ``defa`` or ``defan``) is not a valid Perl regular expression. The actual Perl error message is also given. ``"Bad user-defined plural string: '%s'"`` The plural form(s) of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb`` or ``defadj``) is not a valid Perl interpolated string (usually because it interpolates some undefined variable). ``"Bad .inflectrc file (%s): %s"`` Some other problem occurred in loading the named local or global F<.inflectrc> file. The Perl error message (including the line number) is also given. There are *no* diagnosable run-time error conditions for the actual inflection methods, except ``number_to_words`` and hence no run-time diagnostics. If the inflection methods are unable to form a plural via a user-definition or an inbuilt rule, they just "guess" the commonest English inflection: adding "-s" for nouns, removing "-s" for verbs, and no inflection for adjectives. ``inflect.py`` can raise the following execeptions: ``BadChunkingOptionError`` The optional argument to ``number_to_words()`` wasn't 1, 2 or 3. ``NumOutOfRangeError`` ``number_to_words()`` was passed a number larger than 999,999,999,999,999,999,999,999,999,999,999,999 (that is: nine hundred and ninety-nine decillion, nine hundred and ninety-nine nonillion, nine hundred and ninety-nine octillion, nine hundred and ninety-nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, nine hundred and ninety-nine quadrillion, nine hundred and ninety-nine trillion, nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine :-) The problem is that ``number_to_words`` doesn't know any words for number components bigger than "decillion". .. #TODO expand these ``UnknownClassicalModeError`` ``BadNumValueError`` ``BadUserDefinedPatternError`` ``BadRcFileError`` OTHER ISSUES ============ 2nd Person precedence --------------------- If a verb has identical 1st and 2nd person singular forms, but different 1st and 2nd person plural forms, then when its plural is constructed, the 2nd person plural form is always preferred. The author is not currently aware of any such verbs in English, but is not quite arrogant enough to assume *ipso facto* that none exist. Nominative precedence --------------------- The singular pronoun "it" presents a special problem because its plural form can vary, depending on its "case". For example:: It ate my homework -> They ate my homework It ate it -> They ate them I fed my homework to it -> I fed my homework to them As a consequence of this ambiguity, ``plural()`` or ``plural_noun`` have been implemented so that they always return the *nominative* plural (that is, "they"). However, when asked for the plural of an unambiguously *accusative* "it" (namely, ``plural("to it")``, ``plural_noun("from it")``, ``plural("with it")``, etc.), both methods will correctly return the accusative plural ("to them", "from them", "with them", etc.) The plurality of zero --------------------- The rules governing the choice between:: There were no errors. and :: There was no error. are complex and often depend more on *intent* rather than *content*. Hence it is infeasible to specify such rules algorithmically. Therefore, inflect.py contents itself with the following compromise: If the governing number is zero, inflections always return the plural form unless the appropriate "classical" inflection is in effect, in which case the singular form is always returned. Thus, the sequence:: p.num(0) print(p.inflect("There plural(was) no(choice)")) produces "There were no choices", whereas:: p.classical(zero=True) p.num(0) print(p.inflect("There plural(was) no(choice)")) it will print("There was no choice".) Homographs with heterogeneous plurals ------------------------------------- Another context in which intent (and not content) sometimes determines plurality is where two distinct meanings of a word require different plurals. For example:: Three basses were stolen from the band's equipment trailer. Three bass were stolen from the band's aquarium. I put the mice next to the cheese. I put the mouses next to the computers. Several thoughts about leaving crossed my mind. Several thought about leaving across my lawn. inflect.py handles such words in two ways: - If both meanings of the word are the *same* part of speech (for example, "bass" is a noun in both sentences above), then one meaning is chosen as the "usual" meaning, and only that meaning's plural is ever returned by any of the inflection methods. - If each meaning of the word is a different part of speech (for example, "thought" is both a noun and a verb), then the noun's plural is returned by ``plural()`` and ``plural_noun()`` and the verb's plural is returned only by ``plural_verb()``. Such contexts are, fortunately, uncommon (particularly "same-part-of-speech" examples). An informal study of nearly 600 "difficult plurals" indicates that ``plural()`` can be relied upon to "get it right" about 98% of the time (although, of course, ichthyophilic guitarists or cyber-behaviouralists may experience higher rates of confusion). If the choice of a particular "usual inflection" is considered inappropriate, it can always be reversed with a preliminary call to the corresponding ``def_...`` method. NOTE ==== There will be no further correspondence on: "octopi". Despite the populist pandering of certain New World dictionaries, the plural is "octopuses" or (for the pendantic classicist) "octopodes". The suffix "-pus" is Greek, not Latin, so the plural is "-podes", not "pi". "virus". Had no plural in Latin (possibly because it was a mass noun). The only plural is the Anglicized "viruses". AUTHORS ======= Thorben Krüger (github@benthor.name) * established Python 3 compatibility Paul Dyson (pwdyson@yahoo.com) * converted code from Perl to Python * added singular_noun functionality Original Perl version of the code and documentation: Damian Conway (damian@conway.org), Matthew Persico (ORD inflection) BUGS AND IRRITATIONS ==================== The endless inconsistencies of English. (*Please* report words for which the correct plural or indefinite article is not formed, so that the reliability of inflect.py can be improved.) Keywords: plural,inflect,participle Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Linguistic Provides: inflect Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* inflect-2.1.0/README.rst0000644000076500000240000013725413372337710015231 0ustar jaracostaff00000000000000========== inflect.py ========== .. image:: https://travis-ci.org/jazzband/inflect.svg?branch=master :target: https://travis-ci.org/jazzband/inflect .. image:: https://coveralls.io/repos/github/jazzband/inflect/badge.svg?branch=master :target: https://coveralls.io/github/jazzband/inflect?branch=master .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband This is a `Jazzband `_ project. By contributing you agree to abide by the `Contributor Code of Conduct `_ and follow the `guidelines `_. NAME ==== inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words. INSTALLATION ============ ``pip install inflect`` SYNOPSIS ======== :: import inflect p = inflect.engine() # METHODS: # plural plural_noun plural_verb plural_adj singular_noun no num # compare compare_nouns compare_nouns compare_adjs # a an # present_participle # ordinal number_to_words # join # inflect classical gender # defnoun defverb defadj defa defan # UNCONDITIONALLY FORM THE PLURAL print("The plural of ", word, " is ", p.plural(word)) # CONDITIONALLY FORM THE PLURAL print("I saw", cat_count, p.plural("cat",cat_count)) # FORM PLURALS FOR SPECIFIC PARTS OF SPEECH print(p.plural_noun("I",N1), p.plural_verb("saw",N1), p.plural_adj("my",N2), \) p.plural_noun("saw",N2) # FORM THE SINGULAR OF PLURAL NOUNS print("The singular of ", word, " is ", p.singular_noun(word)) # SELECT THE GENDER OF SINGULAR PRONOUNS print(p.singular_noun('they') # 'it') p.gender('f') print(p.singular_noun('they') # 'she') # DEAL WITH "0/1/N" -> "no/1/N" TRANSLATION: print("There ", p.plural_verb("was",errors), p.no(" error",errors)) # USE DEFAULT COUNTS: print(p.num(N1,""), p.plural("I"), p.plural_verb(" saw"), p.num(N2), p.plural_noun(" saw")) print("There ", p.num(errors,''), p.plural_verb("was"), p.no(" error")) # COMPARE TWO WORDS "NUMBER-INSENSITIVELY": print("same\n" if p.compare(word1, word2)) print("same noun\n" if p.compare_nouns(word1, word2)) print("same verb\n" if p.compare_verbs(word1, word2)) print("same adj.\n" if p.compare_adjs(word1, word2)) # ADD CORRECT "a" OR "an" FOR A GIVEN WORD: print("Did you want ", p.a(thing), " or ", p.an(idea)) # CONVERT NUMERALS INTO ORDINALS (i.e. 1->1st, 2->2nd, 3->3rd, etc.) print("It was", p.ordinal(position), " from the left\n") # CONVERT NUMERALS TO WORDS (i.e. 1->"one", 101->"one hundred and one", etc.) # RETURNS A SINGLE STRING... words = p.number_to_words(1234) # "one thousand, two hundred and thirty-four" words = p.number_to_words(p.ordinal(1234)) # "one thousand, two hundred and thirty-fourth" # GET BACK A LIST OF STRINGS, ONE FOR EACH "CHUNK"... words = p.number_to_words(1234, getlist=True) # ("one thousand","two hundred and thirty-four") # OPTIONAL PARAMETERS CHANGE TRANSLATION: words = p.number_to_words(12345, group=1) # "one, two, three, four, five" words = p.number_to_words(12345, group=2) # "twelve, thirty-four, five" words = p.number_to_words(12345, group=3) # "one twenty-three, forty-five" words = p.number_to_words(1234, andword='') # "one thousand, two hundred thirty-four" words = p.number_to_words(1234, andword=', plus') # "one thousand, two hundred, plus thirty-four" #TODO: I get no comma before plus: check perl words = p.number_to_words(555_1202, group=1, zero='oh') # "five, five, five, one, two, oh, two" words = p.number_to_words(555_1202, group=1, one='unity') # "five, five, five, unity, two, oh, two" words = p.number_to_words(123.456, group=1, decimal='mark') # "one two three mark four five six" #TODO: DOCBUG: perl gives commas here as do I # LITERAL STYLE ONLY NAMES NUMBERS LESS THAN A CERTAIN THRESHOLD... words = p.number_to_words( 9, threshold=10); # "nine" words = p.number_to_words( 10, threshold=10); # "ten" words = p.number_to_words( 11, threshold=10); # "11" words = p.number_to_words(1000, threshold=10); # "1,000" # JOIN WORDS INTO A LIST: mylist = join(("apple", "banana", "carrot")) # "apple, banana, and carrot" mylist = join(("apple", "banana")) # "apple and banana" mylist = join(("apple", "banana", "carrot"), final_sep="") # "apple, banana and carrot" # REQUIRE "CLASSICAL" PLURALS (EG: "focus"->"foci", "cherub"->"cherubim") p.classical() # USE ALL CLASSICAL PLURALS p.classical(all=True) # USE ALL CLASSICAL PLURALS p.classical(all=False) # SWITCH OFF CLASSICAL MODE p.classical(zero=True) # "no error" INSTEAD OF "no errors" p.classical(zero=False) # "no errors" INSTEAD OF "no error" p.classical(herd=True) # "2 buffalo" INSTEAD OF "2 buffalos" p.classical(herd=False) # "2 buffalos" INSTEAD OF "2 buffalo" p.classical(persons=True) # "2 chairpersons" INSTEAD OF "2 chairpeople" p.classical(persons=False) # "2 chairpeople" INSTEAD OF "2 chairpersons" p.classical(ancient=True) # "2 formulae" INSTEAD OF "2 formulas" p.classical(ancient=False) # "2 formulas" INSTEAD OF "2 formulae" # INTERPOLATE "plural()", "plural_noun()", "plural_verb()", "plural_adj()", "singular_noun()", # a()", "an()", "num()" AND "ordinal()" WITHIN STRINGS: print(p.inflect("The plural of {0} is plural({0})".format(word))) print(p.inflect("The singular of {0} is singular_noun({0})".format(word))) print(p.inflect("I saw {0} plural("cat",{0})".format(cat_count))) print(p.inflect("plural(I,{0}) plural_verb(saw,{0}) plural(a,{1}) plural_noun(saw,{1})".format(N1, N2))) print(p.inflect("num({0},)plural(I) plural_verb(saw) num({1},)plural(a) plural_noun(saw)".format(N1, N2))) print(p.inflect("I saw num({0}) plural("cat")\nnum()".format(cat_count))) print(p.inflect("There plural_verb(was,{0}) no(error,{0})".format(errors))) print(p.inflect("There num({0},) plural_verb(was) no(error)".format(errors))) print(p.inflect("Did you want a({0}) or an({1})".format(thing, idea))) print(p.inflect("It was ordinal({0}) from the left".format(position))) # ADD USER-DEFINED INFLECTIONS (OVERRIDING INBUILT RULES): p.defnoun( "VAX", "VAXen" ) # SINGULAR => PLURAL p.defverb( "will" , "shall", # 1ST PERSON SINGULAR => PLURAL "will" , "will", # 2ND PERSON SINGULAR => PLURAL "will" , "will") # 3RD PERSON SINGULAR => PLURAL p.defadj( "hir" , "their") # SINGULAR => PLURAL p.defa("h") # "AY HALWAYS SEZ 'HAITCH'!" p.defan( "horrendous.*" ) # "AN HORRENDOUS AFFECTATION" DESCRIPTION =========== The methods of the class ``engine`` in module ``inflect.py`` provide plural inflections, singular noun inflections, "a"/"an" selection for English words, and manipulation of numbers as words. Plural forms of all nouns, most verbs, and some adjectives are provided. Where appropriate, "classical" variants (for example: "brother" -> "brethren", "dogma" -> "dogmata", etc.) are also provided. Single forms of nouns are also provided. The gender of singular pronouns can be chosen (for example "they" -> "it" or "she" or "he" or "they"). Pronunciation-based "a"/"an" selection is provided for all English words, and most initialisms. It is also possible to inflect numerals (1,2,3) to ordinals (1st, 2nd, 3rd) and to English words ("one", "two", "three"). In generating these inflections, ``inflect.py`` follows the Oxford English Dictionary and the guidelines in Fowler's Modern English Usage, preferring the former where the two disagree. The module is built around standard British spelling, but is designed to cope with common American variants as well. Slang, jargon, and other English dialects are *not* explicitly catered for. Where two or more inflected forms exist for a single word (typically a "classical" form and a "modern" form), ``inflect.py`` prefers the more common form (typically the "modern" one), unless "classical" processing has been specified (see `MODERN VS CLASSICAL INFLECTIONS`). FORMING PLURALS AND SINGULARS ============================= Inflecting Plurals and Singulars -------------------------------- All of the ``plural...`` plural inflection methods take the word to be inflected as their first argument and return the corresponding inflection. Note that all such methods expect the *singular* form of the word. The results of passing a plural form are undefined (and unlikely to be correct). Similarly, the ``si...`` singular inflection method expects the *plural* form of the word. The ``plural...`` methods also take an optional second argument, which indicates the grammatical "number" of the word (or of another word with which the word being inflected must agree). If the "number" argument is supplied and is not ``1`` (or ``"one"`` or ``"a"``, or some other adjective that implies the singular), the plural form of the word is returned. If the "number" argument *does* indicate singularity, the (uninflected) word itself is returned. If the number argument is omitted, the plural form is returned unconditionally. The ``si...`` method takes a second argument in a similar fashion. If it is some form of the number ``1``, or is omitted, the singular form is returned. Otherwise the plural is returned unaltered. The various methods of ``inflect.engine`` are: ``plural_noun(word, count=None)`` The method ``plural_noun()`` takes a *singular* English noun or pronoun and returns its plural. Pronouns in the nominative ("I" -> "we") and accusative ("me" -> "us") cases are handled, as are possessive pronouns ("mine" -> "ours"). ``plural_verb(word, count=None)`` The method ``plural_verb()`` takes the *singular* form of a conjugated verb (that is, one which is already in the correct "person" and "mood") and returns the corresponding plural conjugation. ``plural_adj(word, count=None)`` The method ``plural_adj()`` takes the *singular* form of certain types of adjectives and returns the corresponding plural form. Adjectives that are correctly handled include: "numerical" adjectives ("a" -> "some"), demonstrative adjectives ("this" -> "these", "that" -> "those"), and possessives ("my" -> "our", "cat's" -> "cats'", "child's" -> "childrens'", etc.) ``plural(word, count=None)`` The method ``plural()`` takes a *singular* English noun, pronoun, verb, or adjective and returns its plural form. Where a word has more than one inflection depending on its part of speech (for example, the noun "thought" inflects to "thoughts", the verb "thought" to "thought"), the (singular) noun sense is preferred to the (singular) verb sense. Hence ``plural("knife")`` will return "knives" ("knife" having been treated as a singular noun), whereas ``plural("knifes")`` will return "knife" ("knifes" having been treated as a 3rd person singular verb). The inherent ambiguity of such cases suggests that, where the part of speech is known, ``plural_noun``, ``plural_verb``, and ``plural_adj`` should be used in preference to ``plural``. ``singular_noun(word, count=None)`` The method ``singular_noun()`` takes a *plural* English noun or pronoun and returns its singular. Pronouns in the nominative ("we" -> "I") and accusative ("us" -> "me") cases are handled, as are possessive pronouns ("ours" -> "mine"). When third person singular pronouns are returned they take the neuter gender by default ("they" -> "it"), not ("they"-> "she") nor ("they" -> "he"). This can be changed with ``gender()``. Note that all these methods ignore any whitespace surrounding the word being inflected, but preserve that whitespace when the result is returned. For example, ``plural(" cat ")`` returns " cats ". ``gender(genderletter)`` The third person plural pronoun takes the same form for the female, male and neuter (e.g. "they"). The singular however, depends upon gender (e.g. "she", "he", "it" and "they" -- "they" being the gender neutral form.) By default ``singular_noun`` returns the neuter form, however, the gender can be selected with the ``gender`` method. Pass the first letter of the gender to ``gender`` to return the f(eminine), m(asculine), n(euter) or t(hey) form of the singular. e.g. gender('f') followed by singular_noun('themselves') returns 'herself'. Numbered plurals ---------------- The ``plural...`` methods return only the inflected word, not the count that was used to inflect it. Thus, in order to produce "I saw 3 ducks", it is necessary to use:: print("I saw", N, p.plural_noun(animal,N)) Since the usual purpose of producing a plural is to make it agree with a preceding count, inflect.py provides a method (``no(word, count)``) which, given a word and a(n optional) count, returns the count followed by the correctly inflected word. Hence the previous example can be rewritten:: print("I saw ", p.no(animal,N)) In addition, if the count is zero (or some other term which implies zero, such as ``"zero"``, ``"nil"``, etc.) the count is replaced by the word "no". Hence, if ``N`` had the value zero, the previous example would print(the somewhat more elegant::) I saw no animals rather than:: I saw 0 animals Note that the name of the method is a pun: the method returns either a number (a *No.*) or a ``"no"``, in front of the inflected word. Reducing the number of counts required -------------------------------------- In some contexts, the need to supply an explicit count to the various ``plural...`` methods makes for tiresome repetition. For example:: print(plural_adj("This",errors), plural_noun(" error",errors), \) plural_verb(" was",errors), " fatal." inflect.py therefore provides a method (``num(count=None, show=None)``) which may be used to set a persistent "default number" value. If such a value is set, it is subsequently used whenever an optional second "number" argument is omitted. The default value thus set can subsequently be removed by calling ``num()`` with no arguments. Hence we could rewrite the previous example:: p.num(errors) print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") p.num() Normally, ``num()`` returns its first argument, so that it may also be "inlined" in contexts like:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") However, in certain contexts (see `INTERPOLATING INFLECTIONS IN STRINGS`) it is preferable that ``num()`` return an empty string. Hence ``num()`` provides an optional second argument. If that argument is supplied (that is, if it is defined) and evaluates to false, ``num`` returns an empty string instead of its first argument. For example:: print(p.num(errors,0), p.no("error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Number-insensitive equality --------------------------- inflect.py also provides a solution to the problem of comparing words of differing plurality through the methods ``compare(word1, word2)``, ``compare_nouns(word1, word2)``, ``compare_verbs(word1, word2)``, and ``compare_adjs(word1, word2)``. Each of these methods takes two strings, and compares them using the corresponding plural-inflection method (``plural()``, ``plural_noun()``, ``plural_verb()``, and ``plural_adj()`` respectively). The comparison returns true if: - the strings are equal, or - one string is equal to a plural form of the other, or - the strings are two different plural forms of the one word. Hence all of the following return true:: p.compare("index","index") # RETURNS "eq" p.compare("index","indexes") # RETURNS "s:p" p.compare("index","indices") # RETURNS "s:p" p.compare("indexes","index") # RETURNS "p:s" p.compare("indices","index") # RETURNS "p:s" p.compare("indices","indexes") # RETURNS "p:p" p.compare("indexes","indices") # RETURNS "p:p" p.compare("indices","indices") # RETURNS "eq" As indicated by the comments in the previous example, the actual value returned by the various ``compare`` methods encodes which of the three equality rules succeeded: "eq" is returned if the strings were identical, "s:p" if the strings were singular and plural respectively, "p:s" for plural and singular, and "p:p" for two distinct plurals. Inequality is indicated by returning an empty string. It should be noted that two distinct singular words which happen to take the same plural form are *not* considered equal, nor are cases where one (singular) word's plural is the other (plural) word's singular. Hence all of the following return false:: p.compare("base","basis") # ALTHOUGH BOTH -> "bases" p.compare("syrinx","syringe") # ALTHOUGH BOTH -> "syringes" p.compare("she","he") # ALTHOUGH BOTH -> "they" p.compare("opus","operas") # ALTHOUGH "opus" -> "opera" -> "operas" p.compare("taxi","taxes") # ALTHOUGH "taxi" -> "taxis" -> "taxes" Note too that, although the comparison is "number-insensitive" it is *not* case-insensitive (that is, ``plural("time","Times")`` returns false. To obtain both number and case insensitivity, use the ``lower()`` method on both strings (that is, ``plural("time".lower(), "Times".lower())`` returns true). OTHER VERB FORMS ================ Present participles ------------------- ``inflect.py`` also provides the ``present_participle`` method, which can take a 3rd person singular verb and correctly inflect it to its present participle:: p.present_participle("runs") # "running" p.present_participle("loves") # "loving" p.present_participle("eats") # "eating" p.present_participle("bats") # "batting" p.present_participle("spies") # "spying" PROVIDING INDEFINITE ARTICLES ============================= Selecting indefinite articles ----------------------------- inflect.py provides two methods (``a(word, count=None)`` and ``an(word, count=None)``) which will correctly prepend the appropriate indefinite article to a word, depending on its pronunciation. For example:: p.a("cat") # -> "a cat" p.an("cat") # -> "a cat" p.a("euphemism") # -> "a euphemism" p.a("Euler number") # -> "an Euler number" p.a("hour") # -> "an hour" p.a("houri") # -> "a houri" The two methods are *identical* in function and may be used interchangeably. The only reason that two versions are provided is to enhance the readability of code such as:: print("That is ", an(errortype), " error) print("That is ", a(fataltype), " fatal error) Note that in both cases the actual article provided depends *only* on the pronunciation of the first argument, *not* on the name of the method. ``a()`` and ``an()`` will ignore any indefinite article that already exists at the start of the string. Thus:: half_arked = [ "a elephant", "a giraffe", "an ewe", "a orangutan", ] for txt in half_arked: print(p.a(txt)) # prints: # an elephant # a giraffe # a ewe # an orangutan ``a()`` and ``an()`` both take an optional second argument. As with the ``plural...`` methods, this second argument is a "number" specifier. If its value is ``1`` (or some other value implying singularity), ``a()`` and ``an()`` insert "a" or "an" as appropriate. If the number specifier implies plurality, (``a()`` and ``an()`` insert the actual second argument instead. For example:: p.a("cat",1) # -> "a cat" p.a("cat",2) # -> "2 cat" p.a("cat","one") # -> "one cat" p.a("cat","no") # -> "no cat" Note that, as implied by the previous examples, ``a()`` and ``an()`` both assume that their job is merely to provide the correct qualifier for a word (that is: "a", "an", or the specified count). In other words, they assume that the word they are given has already been correctly inflected for plurality. Hence, if ``N`` has the value 2, then:: print(p.a("cat",N)) prints "2 cat", instead of "2 cats". The correct approach is to use:: print(p.a(p.plural("cat",N),N)) or, better still:: print(p.no("cat",N)) Note too that, like the various ``plural...`` methods, whenever ``a()`` and ``an()`` are called with only one argument they are subject to the effects of any preceding call to ``num()``. Hence, another possible solution is:: p.num(N) print(p.a(p.plural("cat"))) Indefinite articles and initialisms ----------------------------------- "Initialisms" (sometimes inaccurately called "acronyms") are terms which have been formed from the initial letters of words in a phrase (for example, "NATO", "NBL", "S.O.S.", "SCUBA", etc.) Such terms present a particular challenge when selecting between "a" and "an", since they are sometimes pronounced as if they were a single word ("nay-tow", "sku-ba") and sometimes as a series of letter names ("en-eff-ell", "ess-oh-ess"). ``a()`` and ``an()`` cope with this dichotomy using a series of inbuilt rules, which may be summarized as: If the word starts with a single letter, followed by a period or dash (for example, "R.I.P.", "C.O.D.", "e-mail", "X-ray", "T-square"), then choose the appropriate article for the *sound* of the first letter ("an R.I.P.", "a C.O.D.", "an e-mail", "an X-ray", "a T-square"). If the first two letters of the word are capitals, consonants, and do not appear at the start of any known English word, (for example, "LCD", "XML", "YWCA"), then once again choose "a" or "an" depending on the *sound* of the first letter ("an LCD", "an XML", "a YWCA"). Otherwise, assume the string is a capitalized word or a pronounceable initialism (for example, "LED", "OPEC", "FAQ", "UNESCO"), and therefore takes "a" or "an" according to the (apparent) pronunciation of the entire word ("a LED", "an OPEC", "a FAQ", "a UNESCO"). Note that rules 1 and 3 together imply that the presence or absence of punctuation may change the selection of indefinite article for a particular initialism (for example, "a FAQ" but "an F.A.Q."). Indefinite articles and "soft H's" ---------------------------------- Words beginning in the letter 'H' present another type of difficulty when selecting a suitable indefinite article. In a few such words (for example, "hour", "honour", "heir") the 'H' is not voiced at all, and so such words inflect with "an". The remaining cases ("voiced H's") may be divided into two categories: "hard H's" (such as "hangman", "holograph", "hat", etc.) and "soft H's" (such as "hysterical", "horrendous", "holy", etc.) Hard H's always take "a" as their indefinite article, and soft H's normally do so as well. But *some* English speakers prefer "an" for soft H's (although the practice is now generally considered an affectation, rather than a legitimate grammatical alternative). At present, the ``a()`` and ``an()`` methods ignore soft H's and use "a" for any voiced 'H'. The author would, however, welcome feedback on this decision (envisaging a possible future "soft H" mode). INFLECTING ORDINALS =================== Occasionally it is useful to present an integer value as an ordinal rather than as a numeral. For example:: Enter password (1st attempt): ******** Enter password (2nd attempt): ********* Enter password (3rd attempt): ********* No 4th attempt. Access denied. To this end, inflect.py provides the ``ordinal()`` method. ``ordinal()`` takes a single argument and forms its ordinal equivalent. If the argument isn't a numerical integer, it just adds "-th". CONVERTING NUMBERS TO WORDS =========================== The method ``number_to_words`` takes a number (cardinal or ordinal) and returns an English representation of that number. :: word = p.number_to_words(1234567) puts the string:: "one million, two hundred and thirty-four thousand, five hundred and sixty-seven" into ``words``. A list can be return where each comma-separated chunk is returned as a separate element. Hence:: words = p.number_to_words(1234567, wantlist=True) puts the list:: ["one million", "two hundred and thirty-four thousand", "five hundred and sixty-seven"] into ``words``. Non-digits (apart from an optional leading plus or minus sign, any decimal points, and ordinal suffixes -- see below) are silently ignored, so the following all produce identical results:: p.number_to_words(5551202) p.number_to_words(5_551_202) p.number_to_words("5,551,202") p.number_to_words("555-1202") That last case is a little awkward since it's almost certainly a phone number, and "five million, five hundred and fifty-one thousand, two hundred and two" probably isn't what's wanted. To overcome this, ``number_to_words()`` takes an optional argument, 'group', which changes how numbers are translated. The argument must be a positive integer less than four, which indicated how the digits of the number are to be grouped. If the argument is ``1``, then each digit is translated separately. If the argument is ``2``, pairs of digits (starting from the *left*) are grouped together. If the argument is ``3``, triples of numbers (again, from the *left*) are grouped. Hence:: p.number_to_words("555-1202", group=1) returns ``"five, five, five, one, two, zero, two"``, whilst:: p.number_to_words("555-1202", group=2) returns ``"fifty-five, fifty-one, twenty, two"``, and:: p.number_to_words("555-1202", group=3) returns ``"five fifty-five, one twenty, two"``. Phone numbers are often written in words as ``"five..five..five..one..two..zero..two"``, which is also easy to achieve:: join '..', p.number_to_words("555-1202", group=>1) ``number_to_words`` also handles decimal fractions. Hence:: p.number_to_words("1.2345") returns ``"one point two three four five"`` in a scalar context and ``("one","point","two","three","four","five")``) in an array context. Exponent form (``"1.234e56"``) is not yet handled. Multiple decimal points are only translated in one of the "grouping" modes. Hence:: p.number_to_words(101.202.303) returns ``"one hundred and one point two zero two three zero three"``, whereas:: p.number_to_words(101.202.303, group=1) returns ``"one zero one point two zero two point three zero three"``. The digit ``'0'`` is unusual in that in may be translated to English as "zero", "oh", or "nought". To cater for this diversity, ``number_to_words`` may be passed a named argument, 'zero', which may be set to the desired translation of ``'0'``. For example:: print(join "..", p.number_to_words("555-1202", group=3, zero='oh')) prints ``"five..five..five..one..two..oh..two"``. By default, zero is rendered as "zero". Likewise, the digit ``'1'`` may be rendered as "one" or "a/an" (or very occasionally other variants), depending on the context. So there is a ``'one'`` argument as well:: for num in [3,2,1,0]: print(p.number_to_words(num, one='a solitary', zero='no more'),) p.plural(" bottle of beer on the wall", num) # prints: # three bottles of beer on the wall # two bottles of beer on the wall # a solitary bottle of beer on the wall # no more bottles of beer on the wall Care is needed if the word "a/an" is to be used as a ``'one'`` value. Unless the next word is known in advance, it's almost always necessary to use the ``A`` function as well:: for word in ["cat aardvark ewe hour".split()]: print(p.a("{0} {1}".format(p.number_to_words(1, one='a'), word))) # prints: # a cat # an aardvark # a ewe # an hour Another major regional variation in number translation is the use of "and" in certain contexts. The named argument 'and' allows the programmer to specify how "and" should be handled. Hence:: print(scalar p.number_to_words("765", andword='')) prints "seven hundred sixty-five", instead of "seven hundred and sixty-five". By default, the "and" is included. The translation of the decimal point is also subject to variation (with "point", "dot", and "decimal" being the favorites). The named argument 'decimal' allows the programmer to how the decimal point should be rendered. Hence:: print(scalar p.number_to_words("666.124.64.101", group=3, decimal='dot')) prints "six sixty-six, dot, one twenty-four, dot, sixty-four, dot, one zero one" By default, the decimal point is rendered as "point". ``number_to_words`` also handles the ordinal forms of numbers. So:: print(p.number_to_words('1st')) print(p.number_to_words('3rd')) print(p.number_to_words('202nd')) print(p.number_to_words('1000000th')) prints:: first third two hundred and twenty-second one millionth Two common idioms in this regard are:: print(p.number_to_words(ordinal(number))) and:: print(p.ordinal(p.number_to_words(number))) These are identical in effect, except when ``number`` contains a decimal:: number = 99.09 print(p.number_to_words(p.ordinal(number)); # ninety-ninth point zero nine) print(p.ordinal(p.number_to_words(number)); # ninety-nine point zero ninth) Use whichever you feel is most appropriate. CONVERTING LISTS OF WORDS TO PHRASES ==================================== When creating a list of words, commas are used between adjacent items, except if the items contain commas, in which case semicolons are used. But if there are less than two items, the commas/semicolons are omitted entirely. The final item also has a conjunction (usually "and" or "or") before it. And although it's technically incorrect (and sometimes misleading), some people prefer to omit the comma before that final conjunction, even when there are more than two items. That's complicated enough to warrant its own method: ``join()``. This method expects a tuple of words, possibly with one or more options. It returns a string that joins the list together in the normal English usage. For example:: print("You chose ", p.join(selected_items)) # You chose barley soup, roast beef, and Yorkshire pudding print("You chose ", p.join(selected_items, final_sep=>"")) # You chose barley soup, roast beef and Yorkshire pudding print("Please chose ", p.join(side_orders, conj=>"or")) # Please chose salad, vegetables, or ice-cream The available options are:: Option named Specifies Default value conj Final conjunction "and" sep Inter-item separator "," last_sep Final separator value of 'sep' option sep_spaced Space follows sep True conj_spaced Spaces around conj True INTERPOLATING INFLECTIONS IN STRINGS ==================================== By far the commonest use of the inflection methods is to produce message strings for various purposes. For example:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Unfortunately the need to separate each method call detracts significantly from the readability of the resulting code. To ameliorate this problem, inflect.py provides a string-interpolating method (``inflect(txt)``), which recognizes calls to the various inflection methods within a string and interpolates them appropriately. Using ``inflect`` the previous example could be rewritten:: print(p.inflect("num({0}) plural_noun(error) plural_verb(was) detected.".format(errors))) if severity > 1: print(p.inflect("plural_adj(This) plural_noun(error) plural_verb(was) fatal.")) Note that ``inflect`` also correctly handles calls to the ``num()`` method (whether interpolated or antecedent). The ``inflect()`` method has a related extra feature, in that it *automatically* cancels any "default number" value before it returns its interpolated string. This means that calls to ``num()`` which are embedded in an ``inflect()``-interpolated string do not "escape" and interfere with subsequent inflections. MODERN VS CLASSICAL INFLECTIONS =============================== Certain words, mainly of Latin or Ancient Greek origin, can form plurals either using the standard English "-s" suffix, or with their original Latin or Greek inflections. For example:: p.plural("stigma") # -> "stigmas" or "stigmata" p.plural("torus") # -> "toruses" or "tori" p.plural("index") # -> "indexes" or "indices" p.plural("millennium") # -> "millenniums" or "millennia" p.plural("ganglion") # -> "ganglions" or "ganglia" p.plural("octopus") # -> "octopuses" or "octopodes" inflect.py caters to such words by providing an "alternate state" of inflection known as "classical mode". By default, words are inflected using their contemporary English plurals, but if classical mode is invoked, the more traditional plural forms are returned instead. The method ``classical()`` controls this feature. If ``classical()`` is called with no arguments, it unconditionally invokes classical mode. If it is called with a single argument, it turns all classical inflects on or off (depending on whether the argument is true or false). If called with two or more arguments, those arguments specify which aspects of classical behaviour are to be used. Thus:: p.classical() # SWITCH ON CLASSICAL MODE print(p.plural("formula") # -> "formulae") p.classical(all=False) # SWITCH OFF CLASSICAL MODE print(p.plural("formula") # -> "formulas") p.classical(cmode=True) # CLASSICAL MODE IFF cmode print(p.plural("formula") # -> "formulae" (IF cmode)) # -> "formulas" (OTHERWISE) p.classical(herd=True) # SWITCH ON CLASSICAL MODE FOR "HERD" NOUNS print(p.plural("wilderbeest") # -> "wilderbeest") p.classical(names=True) # SWITCH ON CLASSICAL MODE FOR NAMES print(p.plural("sally") # -> "sallies") print(p.plural("Sally") # -> "Sallys") Note however that ``classical()`` has no effect on the inflection of words which are now fully assimilated. Hence:: p.plural("forum") # ALWAYS -> "forums" p.plural("criterion") # ALWAYS -> "criteria" LEI assumes that a capitalized word is a person's name. So it forms the plural according to the rules for names (which is that you don't inflect, you just add -s or -es). You can choose to turn that behaviour off (it's on by the default, even when the module isn't in classical mode) by calling `` classical(names=0) `` USER-DEFINED INFLECTIONS ======================== Adding plurals at run-time -------------------------- inflect.py provides five methods which allow the programmer to override the module's behaviour for specific cases: ``defnoun(singular, plural)`` The ``defnoun`` method takes a pair of string arguments: the singular and the plural forms of the noun being specified. The singular form specifies a pattern to be interpolated (as ``m/^(?:$first_arg)$/i``). Any noun matching this pattern is then replaced by the string in the second argument. The second argument specifies a string which is interpolated after the match succeeds, and is then used as the plural form. For example:: defnoun( 'cow' , 'kine') defnoun( '(.+i)o' , '$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!') Note that both arguments should usually be specified in single quotes, so that they are not interpolated when they are specified, but later (when words are compared to them). As indicated by the last example, care also needs to be taken with certain characters in the second argument, to ensure that they are not unintentionally interpolated during comparison. The second argument string may also specify a second variant of the plural form, to be used when "classical" plurals have been requested. The beginning of the second variant is marked by a '|' character:: defnoun( 'cow' , 'cows|kine') defnoun( '(.+i)o' , '$1os|$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!|varmints') If no classical variant is given, the specified plural form is used in both normal and "classical" modes. .. #TODO: check that the following paragraph is implemented If the second argument is ``None`` instead of a string, then the current user definition for the first argument is removed, and the standard plural inflection(s) restored. Note that in all cases, later plural definitions for a particular singular form replace earlier definitions of the same form. For example:: # FIRST, HIDE THE MODERN FORM.... defnoun( 'aviatrix' , 'aviatrices') # LATER, HIDE THE CLASSICAL FORM... defnoun( 'aviatrix' , 'aviatrixes') # FINALLY, RESTORE THE DEFAULT BEHAVIOUR... defnoun( 'aviatrix' , undef) Special care is also required when defining general patterns and associated specific exceptions: put the more specific cases *after* the general pattern. For example:: defnoun( '(.+)us' , '$1i') # EVERY "-us" TO "-i" defnoun( 'bus' , 'buses') # EXCEPT FOR "bus" This "try-most-recently-defined-first" approach to matching user-defined words is also used by ``defverb``, ``defa`` and ``defan``. ``defverb(s1, p1, s2, p2, s3, p3)`` The ``defverb`` method takes three pairs of string arguments (that is, six arguments in total), specifying the singular and plural forms of the three "persons" of verb. As with ``defnoun``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defverb('am' , 'are', 'are' , 'are|art", 'is' , 'are') defverb('have' , 'have', 'have' , 'have", 'ha(s|th)' , 'have') Note that as with ``defnoun``, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defadj(singular, plural)`` The ``defadj`` method takes a pair of string arguments, which specify the singular and plural forms of the adjective being defined. As with ``defnoun`` and ``defadj``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defadj( 'this' , 'these') defadj( 'red' , 'red|gules') As previously, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defa(pattern)`` and ``defan(pattern)`` The ``defa`` and ``defan`` methods each take a single argument, which specifies a pattern. If a word passed to ``a()`` or ``an()`` matches this pattern, it will be prefixed (unconditionally) with the corresponding indefinite article. For example:: defa( 'error') defa( 'in.+') defan('mistake') defan('error') As with the other ``def_...`` methods, such redefinitions are sequential in effect so that, after the above example, "error" will be inflected with "an". The ``<$HOME/.inflectrc`` file ------------------------------ THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET When it is imported, inflect.py executes (as Perl code) the contents of any file named ``.inflectrc`` which it finds in the in the directory where ``Lingua/EN/Inflect.pm`` is installed, or in the current home directory (``$ENV{HOME}``), or in both. Note that the code is executed within the inflect.py namespace. Hence the user or the local Perl guru can make appropriate calls to ``defnoun``, ``defverb``, etc. in one of these ``.inflectrc`` files, to permanently and universally modify the behaviour of the module. For example > cat /usr/local/lib/perl5/Text/Inflect/.inflectrc defnoun "UNIX" => "UN*X|UNICES" defverb "teco" => "teco", # LITERALLY: "to edit with TECO" "teco" => "teco", "tecos" => "teco" defa "Euler.*"; # "Yewler" TURNS IN HIS GRAVE Note that calls to the ``def_...`` methods from within a program will take precedence over the contents of the home directory F<.inflectrc> file, which in turn takes precedence over the system-wide F<.inflectrc> file. DIAGNOSTICS =========== THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET On loading, if the Perl code in a ``.inflectrc`` file is invalid (syntactically or otherwise), an appropriate fatal error is issued. A common problem is not ending the file with something that evaluates to true (as the five ``def_...`` methods do). Using the five ``def_...`` methods directly in a program may also result in fatal diagnostics, if a (singular) pattern or an interpolated (plural) string is somehow invalid. Specific diagnostics related to user-defined inflections are: ``"Bad user-defined singular pattern:\t %s"`` The singular form of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb``, ``defadj``, ``defa`` or ``defan``) is not a valid Perl regular expression. The actual Perl error message is also given. ``"Bad user-defined plural string: '%s'"`` The plural form(s) of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb`` or ``defadj``) is not a valid Perl interpolated string (usually because it interpolates some undefined variable). ``"Bad .inflectrc file (%s): %s"`` Some other problem occurred in loading the named local or global F<.inflectrc> file. The Perl error message (including the line number) is also given. There are *no* diagnosable run-time error conditions for the actual inflection methods, except ``number_to_words`` and hence no run-time diagnostics. If the inflection methods are unable to form a plural via a user-definition or an inbuilt rule, they just "guess" the commonest English inflection: adding "-s" for nouns, removing "-s" for verbs, and no inflection for adjectives. ``inflect.py`` can raise the following execeptions: ``BadChunkingOptionError`` The optional argument to ``number_to_words()`` wasn't 1, 2 or 3. ``NumOutOfRangeError`` ``number_to_words()`` was passed a number larger than 999,999,999,999,999,999,999,999,999,999,999,999 (that is: nine hundred and ninety-nine decillion, nine hundred and ninety-nine nonillion, nine hundred and ninety-nine octillion, nine hundred and ninety-nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, nine hundred and ninety-nine quadrillion, nine hundred and ninety-nine trillion, nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine :-) The problem is that ``number_to_words`` doesn't know any words for number components bigger than "decillion". .. #TODO expand these ``UnknownClassicalModeError`` ``BadNumValueError`` ``BadUserDefinedPatternError`` ``BadRcFileError`` OTHER ISSUES ============ 2nd Person precedence --------------------- If a verb has identical 1st and 2nd person singular forms, but different 1st and 2nd person plural forms, then when its plural is constructed, the 2nd person plural form is always preferred. The author is not currently aware of any such verbs in English, but is not quite arrogant enough to assume *ipso facto* that none exist. Nominative precedence --------------------- The singular pronoun "it" presents a special problem because its plural form can vary, depending on its "case". For example:: It ate my homework -> They ate my homework It ate it -> They ate them I fed my homework to it -> I fed my homework to them As a consequence of this ambiguity, ``plural()`` or ``plural_noun`` have been implemented so that they always return the *nominative* plural (that is, "they"). However, when asked for the plural of an unambiguously *accusative* "it" (namely, ``plural("to it")``, ``plural_noun("from it")``, ``plural("with it")``, etc.), both methods will correctly return the accusative plural ("to them", "from them", "with them", etc.) The plurality of zero --------------------- The rules governing the choice between:: There were no errors. and :: There was no error. are complex and often depend more on *intent* rather than *content*. Hence it is infeasible to specify such rules algorithmically. Therefore, inflect.py contents itself with the following compromise: If the governing number is zero, inflections always return the plural form unless the appropriate "classical" inflection is in effect, in which case the singular form is always returned. Thus, the sequence:: p.num(0) print(p.inflect("There plural(was) no(choice)")) produces "There were no choices", whereas:: p.classical(zero=True) p.num(0) print(p.inflect("There plural(was) no(choice)")) it will print("There was no choice".) Homographs with heterogeneous plurals ------------------------------------- Another context in which intent (and not content) sometimes determines plurality is where two distinct meanings of a word require different plurals. For example:: Three basses were stolen from the band's equipment trailer. Three bass were stolen from the band's aquarium. I put the mice next to the cheese. I put the mouses next to the computers. Several thoughts about leaving crossed my mind. Several thought about leaving across my lawn. inflect.py handles such words in two ways: - If both meanings of the word are the *same* part of speech (for example, "bass" is a noun in both sentences above), then one meaning is chosen as the "usual" meaning, and only that meaning's plural is ever returned by any of the inflection methods. - If each meaning of the word is a different part of speech (for example, "thought" is both a noun and a verb), then the noun's plural is returned by ``plural()`` and ``plural_noun()`` and the verb's plural is returned only by ``plural_verb()``. Such contexts are, fortunately, uncommon (particularly "same-part-of-speech" examples). An informal study of nearly 600 "difficult plurals" indicates that ``plural()`` can be relied upon to "get it right" about 98% of the time (although, of course, ichthyophilic guitarists or cyber-behaviouralists may experience higher rates of confusion). If the choice of a particular "usual inflection" is considered inappropriate, it can always be reversed with a preliminary call to the corresponding ``def_...`` method. NOTE ==== There will be no further correspondence on: "octopi". Despite the populist pandering of certain New World dictionaries, the plural is "octopuses" or (for the pendantic classicist) "octopodes". The suffix "-pus" is Greek, not Latin, so the plural is "-podes", not "pi". "virus". Had no plural in Latin (possibly because it was a mass noun). The only plural is the Anglicized "viruses". AUTHORS ======= Thorben Krüger (github@benthor.name) * established Python 3 compatibility Paul Dyson (pwdyson@yahoo.com) * converted code from Perl to Python * added singular_noun functionality Original Perl version of the code and documentation: Damian Conway (damian@conway.org), Matthew Persico (ORD inflection) BUGS AND IRRITATIONS ==================== The endless inconsistencies of English. (*Please* report words for which the correct plural or indefinite article is not formed, so that the reliability of inflect.py can be improved.) inflect-2.1.0/inflect.egg-info/0000755000076500000240000000000013372337712016646 5ustar jaracostaff00000000000000inflect-2.1.0/inflect.egg-info/PKG-INFO0000644000076500000240000016654713372337712017766 0ustar jaracostaff00000000000000Metadata-Version: 1.2 Name: inflect Version: 2.1.0 Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words Home-page: https://github.com/jazzband/inflect Author: Paul Dyson Author-email: pwdyson@yahoo.com Maintainer: Alex Gronholm Maintainer-email: alex.gronholm@nextday.fi License: UNKNOWN Description: ========== inflect.py ========== .. image:: https://travis-ci.org/jazzband/inflect.svg?branch=master :target: https://travis-ci.org/jazzband/inflect .. image:: https://coveralls.io/repos/github/jazzband/inflect/badge.svg?branch=master :target: https://coveralls.io/github/jazzband/inflect?branch=master .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: Black .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband This is a `Jazzband `_ project. By contributing you agree to abide by the `Contributor Code of Conduct `_ and follow the `guidelines `_. NAME ==== inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words. INSTALLATION ============ ``pip install inflect`` SYNOPSIS ======== :: import inflect p = inflect.engine() # METHODS: # plural plural_noun plural_verb plural_adj singular_noun no num # compare compare_nouns compare_nouns compare_adjs # a an # present_participle # ordinal number_to_words # join # inflect classical gender # defnoun defverb defadj defa defan # UNCONDITIONALLY FORM THE PLURAL print("The plural of ", word, " is ", p.plural(word)) # CONDITIONALLY FORM THE PLURAL print("I saw", cat_count, p.plural("cat",cat_count)) # FORM PLURALS FOR SPECIFIC PARTS OF SPEECH print(p.plural_noun("I",N1), p.plural_verb("saw",N1), p.plural_adj("my",N2), \) p.plural_noun("saw",N2) # FORM THE SINGULAR OF PLURAL NOUNS print("The singular of ", word, " is ", p.singular_noun(word)) # SELECT THE GENDER OF SINGULAR PRONOUNS print(p.singular_noun('they') # 'it') p.gender('f') print(p.singular_noun('they') # 'she') # DEAL WITH "0/1/N" -> "no/1/N" TRANSLATION: print("There ", p.plural_verb("was",errors), p.no(" error",errors)) # USE DEFAULT COUNTS: print(p.num(N1,""), p.plural("I"), p.plural_verb(" saw"), p.num(N2), p.plural_noun(" saw")) print("There ", p.num(errors,''), p.plural_verb("was"), p.no(" error")) # COMPARE TWO WORDS "NUMBER-INSENSITIVELY": print("same\n" if p.compare(word1, word2)) print("same noun\n" if p.compare_nouns(word1, word2)) print("same verb\n" if p.compare_verbs(word1, word2)) print("same adj.\n" if p.compare_adjs(word1, word2)) # ADD CORRECT "a" OR "an" FOR A GIVEN WORD: print("Did you want ", p.a(thing), " or ", p.an(idea)) # CONVERT NUMERALS INTO ORDINALS (i.e. 1->1st, 2->2nd, 3->3rd, etc.) print("It was", p.ordinal(position), " from the left\n") # CONVERT NUMERALS TO WORDS (i.e. 1->"one", 101->"one hundred and one", etc.) # RETURNS A SINGLE STRING... words = p.number_to_words(1234) # "one thousand, two hundred and thirty-four" words = p.number_to_words(p.ordinal(1234)) # "one thousand, two hundred and thirty-fourth" # GET BACK A LIST OF STRINGS, ONE FOR EACH "CHUNK"... words = p.number_to_words(1234, getlist=True) # ("one thousand","two hundred and thirty-four") # OPTIONAL PARAMETERS CHANGE TRANSLATION: words = p.number_to_words(12345, group=1) # "one, two, three, four, five" words = p.number_to_words(12345, group=2) # "twelve, thirty-four, five" words = p.number_to_words(12345, group=3) # "one twenty-three, forty-five" words = p.number_to_words(1234, andword='') # "one thousand, two hundred thirty-four" words = p.number_to_words(1234, andword=', plus') # "one thousand, two hundred, plus thirty-four" #TODO: I get no comma before plus: check perl words = p.number_to_words(555_1202, group=1, zero='oh') # "five, five, five, one, two, oh, two" words = p.number_to_words(555_1202, group=1, one='unity') # "five, five, five, unity, two, oh, two" words = p.number_to_words(123.456, group=1, decimal='mark') # "one two three mark four five six" #TODO: DOCBUG: perl gives commas here as do I # LITERAL STYLE ONLY NAMES NUMBERS LESS THAN A CERTAIN THRESHOLD... words = p.number_to_words( 9, threshold=10); # "nine" words = p.number_to_words( 10, threshold=10); # "ten" words = p.number_to_words( 11, threshold=10); # "11" words = p.number_to_words(1000, threshold=10); # "1,000" # JOIN WORDS INTO A LIST: mylist = join(("apple", "banana", "carrot")) # "apple, banana, and carrot" mylist = join(("apple", "banana")) # "apple and banana" mylist = join(("apple", "banana", "carrot"), final_sep="") # "apple, banana and carrot" # REQUIRE "CLASSICAL" PLURALS (EG: "focus"->"foci", "cherub"->"cherubim") p.classical() # USE ALL CLASSICAL PLURALS p.classical(all=True) # USE ALL CLASSICAL PLURALS p.classical(all=False) # SWITCH OFF CLASSICAL MODE p.classical(zero=True) # "no error" INSTEAD OF "no errors" p.classical(zero=False) # "no errors" INSTEAD OF "no error" p.classical(herd=True) # "2 buffalo" INSTEAD OF "2 buffalos" p.classical(herd=False) # "2 buffalos" INSTEAD OF "2 buffalo" p.classical(persons=True) # "2 chairpersons" INSTEAD OF "2 chairpeople" p.classical(persons=False) # "2 chairpeople" INSTEAD OF "2 chairpersons" p.classical(ancient=True) # "2 formulae" INSTEAD OF "2 formulas" p.classical(ancient=False) # "2 formulas" INSTEAD OF "2 formulae" # INTERPOLATE "plural()", "plural_noun()", "plural_verb()", "plural_adj()", "singular_noun()", # a()", "an()", "num()" AND "ordinal()" WITHIN STRINGS: print(p.inflect("The plural of {0} is plural({0})".format(word))) print(p.inflect("The singular of {0} is singular_noun({0})".format(word))) print(p.inflect("I saw {0} plural("cat",{0})".format(cat_count))) print(p.inflect("plural(I,{0}) plural_verb(saw,{0}) plural(a,{1}) plural_noun(saw,{1})".format(N1, N2))) print(p.inflect("num({0},)plural(I) plural_verb(saw) num({1},)plural(a) plural_noun(saw)".format(N1, N2))) print(p.inflect("I saw num({0}) plural("cat")\nnum()".format(cat_count))) print(p.inflect("There plural_verb(was,{0}) no(error,{0})".format(errors))) print(p.inflect("There num({0},) plural_verb(was) no(error)".format(errors))) print(p.inflect("Did you want a({0}) or an({1})".format(thing, idea))) print(p.inflect("It was ordinal({0}) from the left".format(position))) # ADD USER-DEFINED INFLECTIONS (OVERRIDING INBUILT RULES): p.defnoun( "VAX", "VAXen" ) # SINGULAR => PLURAL p.defverb( "will" , "shall", # 1ST PERSON SINGULAR => PLURAL "will" , "will", # 2ND PERSON SINGULAR => PLURAL "will" , "will") # 3RD PERSON SINGULAR => PLURAL p.defadj( "hir" , "their") # SINGULAR => PLURAL p.defa("h") # "AY HALWAYS SEZ 'HAITCH'!" p.defan( "horrendous.*" ) # "AN HORRENDOUS AFFECTATION" DESCRIPTION =========== The methods of the class ``engine`` in module ``inflect.py`` provide plural inflections, singular noun inflections, "a"/"an" selection for English words, and manipulation of numbers as words. Plural forms of all nouns, most verbs, and some adjectives are provided. Where appropriate, "classical" variants (for example: "brother" -> "brethren", "dogma" -> "dogmata", etc.) are also provided. Single forms of nouns are also provided. The gender of singular pronouns can be chosen (for example "they" -> "it" or "she" or "he" or "they"). Pronunciation-based "a"/"an" selection is provided for all English words, and most initialisms. It is also possible to inflect numerals (1,2,3) to ordinals (1st, 2nd, 3rd) and to English words ("one", "two", "three"). In generating these inflections, ``inflect.py`` follows the Oxford English Dictionary and the guidelines in Fowler's Modern English Usage, preferring the former where the two disagree. The module is built around standard British spelling, but is designed to cope with common American variants as well. Slang, jargon, and other English dialects are *not* explicitly catered for. Where two or more inflected forms exist for a single word (typically a "classical" form and a "modern" form), ``inflect.py`` prefers the more common form (typically the "modern" one), unless "classical" processing has been specified (see `MODERN VS CLASSICAL INFLECTIONS`). FORMING PLURALS AND SINGULARS ============================= Inflecting Plurals and Singulars -------------------------------- All of the ``plural...`` plural inflection methods take the word to be inflected as their first argument and return the corresponding inflection. Note that all such methods expect the *singular* form of the word. The results of passing a plural form are undefined (and unlikely to be correct). Similarly, the ``si...`` singular inflection method expects the *plural* form of the word. The ``plural...`` methods also take an optional second argument, which indicates the grammatical "number" of the word (or of another word with which the word being inflected must agree). If the "number" argument is supplied and is not ``1`` (or ``"one"`` or ``"a"``, or some other adjective that implies the singular), the plural form of the word is returned. If the "number" argument *does* indicate singularity, the (uninflected) word itself is returned. If the number argument is omitted, the plural form is returned unconditionally. The ``si...`` method takes a second argument in a similar fashion. If it is some form of the number ``1``, or is omitted, the singular form is returned. Otherwise the plural is returned unaltered. The various methods of ``inflect.engine`` are: ``plural_noun(word, count=None)`` The method ``plural_noun()`` takes a *singular* English noun or pronoun and returns its plural. Pronouns in the nominative ("I" -> "we") and accusative ("me" -> "us") cases are handled, as are possessive pronouns ("mine" -> "ours"). ``plural_verb(word, count=None)`` The method ``plural_verb()`` takes the *singular* form of a conjugated verb (that is, one which is already in the correct "person" and "mood") and returns the corresponding plural conjugation. ``plural_adj(word, count=None)`` The method ``plural_adj()`` takes the *singular* form of certain types of adjectives and returns the corresponding plural form. Adjectives that are correctly handled include: "numerical" adjectives ("a" -> "some"), demonstrative adjectives ("this" -> "these", "that" -> "those"), and possessives ("my" -> "our", "cat's" -> "cats'", "child's" -> "childrens'", etc.) ``plural(word, count=None)`` The method ``plural()`` takes a *singular* English noun, pronoun, verb, or adjective and returns its plural form. Where a word has more than one inflection depending on its part of speech (for example, the noun "thought" inflects to "thoughts", the verb "thought" to "thought"), the (singular) noun sense is preferred to the (singular) verb sense. Hence ``plural("knife")`` will return "knives" ("knife" having been treated as a singular noun), whereas ``plural("knifes")`` will return "knife" ("knifes" having been treated as a 3rd person singular verb). The inherent ambiguity of such cases suggests that, where the part of speech is known, ``plural_noun``, ``plural_verb``, and ``plural_adj`` should be used in preference to ``plural``. ``singular_noun(word, count=None)`` The method ``singular_noun()`` takes a *plural* English noun or pronoun and returns its singular. Pronouns in the nominative ("we" -> "I") and accusative ("us" -> "me") cases are handled, as are possessive pronouns ("ours" -> "mine"). When third person singular pronouns are returned they take the neuter gender by default ("they" -> "it"), not ("they"-> "she") nor ("they" -> "he"). This can be changed with ``gender()``. Note that all these methods ignore any whitespace surrounding the word being inflected, but preserve that whitespace when the result is returned. For example, ``plural(" cat ")`` returns " cats ". ``gender(genderletter)`` The third person plural pronoun takes the same form for the female, male and neuter (e.g. "they"). The singular however, depends upon gender (e.g. "she", "he", "it" and "they" -- "they" being the gender neutral form.) By default ``singular_noun`` returns the neuter form, however, the gender can be selected with the ``gender`` method. Pass the first letter of the gender to ``gender`` to return the f(eminine), m(asculine), n(euter) or t(hey) form of the singular. e.g. gender('f') followed by singular_noun('themselves') returns 'herself'. Numbered plurals ---------------- The ``plural...`` methods return only the inflected word, not the count that was used to inflect it. Thus, in order to produce "I saw 3 ducks", it is necessary to use:: print("I saw", N, p.plural_noun(animal,N)) Since the usual purpose of producing a plural is to make it agree with a preceding count, inflect.py provides a method (``no(word, count)``) which, given a word and a(n optional) count, returns the count followed by the correctly inflected word. Hence the previous example can be rewritten:: print("I saw ", p.no(animal,N)) In addition, if the count is zero (or some other term which implies zero, such as ``"zero"``, ``"nil"``, etc.) the count is replaced by the word "no". Hence, if ``N`` had the value zero, the previous example would print(the somewhat more elegant::) I saw no animals rather than:: I saw 0 animals Note that the name of the method is a pun: the method returns either a number (a *No.*) or a ``"no"``, in front of the inflected word. Reducing the number of counts required -------------------------------------- In some contexts, the need to supply an explicit count to the various ``plural...`` methods makes for tiresome repetition. For example:: print(plural_adj("This",errors), plural_noun(" error",errors), \) plural_verb(" was",errors), " fatal." inflect.py therefore provides a method (``num(count=None, show=None)``) which may be used to set a persistent "default number" value. If such a value is set, it is subsequently used whenever an optional second "number" argument is omitted. The default value thus set can subsequently be removed by calling ``num()`` with no arguments. Hence we could rewrite the previous example:: p.num(errors) print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") p.num() Normally, ``num()`` returns its first argument, so that it may also be "inlined" in contexts like:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") However, in certain contexts (see `INTERPOLATING INFLECTIONS IN STRINGS`) it is preferable that ``num()`` return an empty string. Hence ``num()`` provides an optional second argument. If that argument is supplied (that is, if it is defined) and evaluates to false, ``num`` returns an empty string instead of its first argument. For example:: print(p.num(errors,0), p.no("error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Number-insensitive equality --------------------------- inflect.py also provides a solution to the problem of comparing words of differing plurality through the methods ``compare(word1, word2)``, ``compare_nouns(word1, word2)``, ``compare_verbs(word1, word2)``, and ``compare_adjs(word1, word2)``. Each of these methods takes two strings, and compares them using the corresponding plural-inflection method (``plural()``, ``plural_noun()``, ``plural_verb()``, and ``plural_adj()`` respectively). The comparison returns true if: - the strings are equal, or - one string is equal to a plural form of the other, or - the strings are two different plural forms of the one word. Hence all of the following return true:: p.compare("index","index") # RETURNS "eq" p.compare("index","indexes") # RETURNS "s:p" p.compare("index","indices") # RETURNS "s:p" p.compare("indexes","index") # RETURNS "p:s" p.compare("indices","index") # RETURNS "p:s" p.compare("indices","indexes") # RETURNS "p:p" p.compare("indexes","indices") # RETURNS "p:p" p.compare("indices","indices") # RETURNS "eq" As indicated by the comments in the previous example, the actual value returned by the various ``compare`` methods encodes which of the three equality rules succeeded: "eq" is returned if the strings were identical, "s:p" if the strings were singular and plural respectively, "p:s" for plural and singular, and "p:p" for two distinct plurals. Inequality is indicated by returning an empty string. It should be noted that two distinct singular words which happen to take the same plural form are *not* considered equal, nor are cases where one (singular) word's plural is the other (plural) word's singular. Hence all of the following return false:: p.compare("base","basis") # ALTHOUGH BOTH -> "bases" p.compare("syrinx","syringe") # ALTHOUGH BOTH -> "syringes" p.compare("she","he") # ALTHOUGH BOTH -> "they" p.compare("opus","operas") # ALTHOUGH "opus" -> "opera" -> "operas" p.compare("taxi","taxes") # ALTHOUGH "taxi" -> "taxis" -> "taxes" Note too that, although the comparison is "number-insensitive" it is *not* case-insensitive (that is, ``plural("time","Times")`` returns false. To obtain both number and case insensitivity, use the ``lower()`` method on both strings (that is, ``plural("time".lower(), "Times".lower())`` returns true). OTHER VERB FORMS ================ Present participles ------------------- ``inflect.py`` also provides the ``present_participle`` method, which can take a 3rd person singular verb and correctly inflect it to its present participle:: p.present_participle("runs") # "running" p.present_participle("loves") # "loving" p.present_participle("eats") # "eating" p.present_participle("bats") # "batting" p.present_participle("spies") # "spying" PROVIDING INDEFINITE ARTICLES ============================= Selecting indefinite articles ----------------------------- inflect.py provides two methods (``a(word, count=None)`` and ``an(word, count=None)``) which will correctly prepend the appropriate indefinite article to a word, depending on its pronunciation. For example:: p.a("cat") # -> "a cat" p.an("cat") # -> "a cat" p.a("euphemism") # -> "a euphemism" p.a("Euler number") # -> "an Euler number" p.a("hour") # -> "an hour" p.a("houri") # -> "a houri" The two methods are *identical* in function and may be used interchangeably. The only reason that two versions are provided is to enhance the readability of code such as:: print("That is ", an(errortype), " error) print("That is ", a(fataltype), " fatal error) Note that in both cases the actual article provided depends *only* on the pronunciation of the first argument, *not* on the name of the method. ``a()`` and ``an()`` will ignore any indefinite article that already exists at the start of the string. Thus:: half_arked = [ "a elephant", "a giraffe", "an ewe", "a orangutan", ] for txt in half_arked: print(p.a(txt)) # prints: # an elephant # a giraffe # a ewe # an orangutan ``a()`` and ``an()`` both take an optional second argument. As with the ``plural...`` methods, this second argument is a "number" specifier. If its value is ``1`` (or some other value implying singularity), ``a()`` and ``an()`` insert "a" or "an" as appropriate. If the number specifier implies plurality, (``a()`` and ``an()`` insert the actual second argument instead. For example:: p.a("cat",1) # -> "a cat" p.a("cat",2) # -> "2 cat" p.a("cat","one") # -> "one cat" p.a("cat","no") # -> "no cat" Note that, as implied by the previous examples, ``a()`` and ``an()`` both assume that their job is merely to provide the correct qualifier for a word (that is: "a", "an", or the specified count). In other words, they assume that the word they are given has already been correctly inflected for plurality. Hence, if ``N`` has the value 2, then:: print(p.a("cat",N)) prints "2 cat", instead of "2 cats". The correct approach is to use:: print(p.a(p.plural("cat",N),N)) or, better still:: print(p.no("cat",N)) Note too that, like the various ``plural...`` methods, whenever ``a()`` and ``an()`` are called with only one argument they are subject to the effects of any preceding call to ``num()``. Hence, another possible solution is:: p.num(N) print(p.a(p.plural("cat"))) Indefinite articles and initialisms ----------------------------------- "Initialisms" (sometimes inaccurately called "acronyms") are terms which have been formed from the initial letters of words in a phrase (for example, "NATO", "NBL", "S.O.S.", "SCUBA", etc.) Such terms present a particular challenge when selecting between "a" and "an", since they are sometimes pronounced as if they were a single word ("nay-tow", "sku-ba") and sometimes as a series of letter names ("en-eff-ell", "ess-oh-ess"). ``a()`` and ``an()`` cope with this dichotomy using a series of inbuilt rules, which may be summarized as: If the word starts with a single letter, followed by a period or dash (for example, "R.I.P.", "C.O.D.", "e-mail", "X-ray", "T-square"), then choose the appropriate article for the *sound* of the first letter ("an R.I.P.", "a C.O.D.", "an e-mail", "an X-ray", "a T-square"). If the first two letters of the word are capitals, consonants, and do not appear at the start of any known English word, (for example, "LCD", "XML", "YWCA"), then once again choose "a" or "an" depending on the *sound* of the first letter ("an LCD", "an XML", "a YWCA"). Otherwise, assume the string is a capitalized word or a pronounceable initialism (for example, "LED", "OPEC", "FAQ", "UNESCO"), and therefore takes "a" or "an" according to the (apparent) pronunciation of the entire word ("a LED", "an OPEC", "a FAQ", "a UNESCO"). Note that rules 1 and 3 together imply that the presence or absence of punctuation may change the selection of indefinite article for a particular initialism (for example, "a FAQ" but "an F.A.Q."). Indefinite articles and "soft H's" ---------------------------------- Words beginning in the letter 'H' present another type of difficulty when selecting a suitable indefinite article. In a few such words (for example, "hour", "honour", "heir") the 'H' is not voiced at all, and so such words inflect with "an". The remaining cases ("voiced H's") may be divided into two categories: "hard H's" (such as "hangman", "holograph", "hat", etc.) and "soft H's" (such as "hysterical", "horrendous", "holy", etc.) Hard H's always take "a" as their indefinite article, and soft H's normally do so as well. But *some* English speakers prefer "an" for soft H's (although the practice is now generally considered an affectation, rather than a legitimate grammatical alternative). At present, the ``a()`` and ``an()`` methods ignore soft H's and use "a" for any voiced 'H'. The author would, however, welcome feedback on this decision (envisaging a possible future "soft H" mode). INFLECTING ORDINALS =================== Occasionally it is useful to present an integer value as an ordinal rather than as a numeral. For example:: Enter password (1st attempt): ******** Enter password (2nd attempt): ********* Enter password (3rd attempt): ********* No 4th attempt. Access denied. To this end, inflect.py provides the ``ordinal()`` method. ``ordinal()`` takes a single argument and forms its ordinal equivalent. If the argument isn't a numerical integer, it just adds "-th". CONVERTING NUMBERS TO WORDS =========================== The method ``number_to_words`` takes a number (cardinal or ordinal) and returns an English representation of that number. :: word = p.number_to_words(1234567) puts the string:: "one million, two hundred and thirty-four thousand, five hundred and sixty-seven" into ``words``. A list can be return where each comma-separated chunk is returned as a separate element. Hence:: words = p.number_to_words(1234567, wantlist=True) puts the list:: ["one million", "two hundred and thirty-four thousand", "five hundred and sixty-seven"] into ``words``. Non-digits (apart from an optional leading plus or minus sign, any decimal points, and ordinal suffixes -- see below) are silently ignored, so the following all produce identical results:: p.number_to_words(5551202) p.number_to_words(5_551_202) p.number_to_words("5,551,202") p.number_to_words("555-1202") That last case is a little awkward since it's almost certainly a phone number, and "five million, five hundred and fifty-one thousand, two hundred and two" probably isn't what's wanted. To overcome this, ``number_to_words()`` takes an optional argument, 'group', which changes how numbers are translated. The argument must be a positive integer less than four, which indicated how the digits of the number are to be grouped. If the argument is ``1``, then each digit is translated separately. If the argument is ``2``, pairs of digits (starting from the *left*) are grouped together. If the argument is ``3``, triples of numbers (again, from the *left*) are grouped. Hence:: p.number_to_words("555-1202", group=1) returns ``"five, five, five, one, two, zero, two"``, whilst:: p.number_to_words("555-1202", group=2) returns ``"fifty-five, fifty-one, twenty, two"``, and:: p.number_to_words("555-1202", group=3) returns ``"five fifty-five, one twenty, two"``. Phone numbers are often written in words as ``"five..five..five..one..two..zero..two"``, which is also easy to achieve:: join '..', p.number_to_words("555-1202", group=>1) ``number_to_words`` also handles decimal fractions. Hence:: p.number_to_words("1.2345") returns ``"one point two three four five"`` in a scalar context and ``("one","point","two","three","four","five")``) in an array context. Exponent form (``"1.234e56"``) is not yet handled. Multiple decimal points are only translated in one of the "grouping" modes. Hence:: p.number_to_words(101.202.303) returns ``"one hundred and one point two zero two three zero three"``, whereas:: p.number_to_words(101.202.303, group=1) returns ``"one zero one point two zero two point three zero three"``. The digit ``'0'`` is unusual in that in may be translated to English as "zero", "oh", or "nought". To cater for this diversity, ``number_to_words`` may be passed a named argument, 'zero', which may be set to the desired translation of ``'0'``. For example:: print(join "..", p.number_to_words("555-1202", group=3, zero='oh')) prints ``"five..five..five..one..two..oh..two"``. By default, zero is rendered as "zero". Likewise, the digit ``'1'`` may be rendered as "one" or "a/an" (or very occasionally other variants), depending on the context. So there is a ``'one'`` argument as well:: for num in [3,2,1,0]: print(p.number_to_words(num, one='a solitary', zero='no more'),) p.plural(" bottle of beer on the wall", num) # prints: # three bottles of beer on the wall # two bottles of beer on the wall # a solitary bottle of beer on the wall # no more bottles of beer on the wall Care is needed if the word "a/an" is to be used as a ``'one'`` value. Unless the next word is known in advance, it's almost always necessary to use the ``A`` function as well:: for word in ["cat aardvark ewe hour".split()]: print(p.a("{0} {1}".format(p.number_to_words(1, one='a'), word))) # prints: # a cat # an aardvark # a ewe # an hour Another major regional variation in number translation is the use of "and" in certain contexts. The named argument 'and' allows the programmer to specify how "and" should be handled. Hence:: print(scalar p.number_to_words("765", andword='')) prints "seven hundred sixty-five", instead of "seven hundred and sixty-five". By default, the "and" is included. The translation of the decimal point is also subject to variation (with "point", "dot", and "decimal" being the favorites). The named argument 'decimal' allows the programmer to how the decimal point should be rendered. Hence:: print(scalar p.number_to_words("666.124.64.101", group=3, decimal='dot')) prints "six sixty-six, dot, one twenty-four, dot, sixty-four, dot, one zero one" By default, the decimal point is rendered as "point". ``number_to_words`` also handles the ordinal forms of numbers. So:: print(p.number_to_words('1st')) print(p.number_to_words('3rd')) print(p.number_to_words('202nd')) print(p.number_to_words('1000000th')) prints:: first third two hundred and twenty-second one millionth Two common idioms in this regard are:: print(p.number_to_words(ordinal(number))) and:: print(p.ordinal(p.number_to_words(number))) These are identical in effect, except when ``number`` contains a decimal:: number = 99.09 print(p.number_to_words(p.ordinal(number)); # ninety-ninth point zero nine) print(p.ordinal(p.number_to_words(number)); # ninety-nine point zero ninth) Use whichever you feel is most appropriate. CONVERTING LISTS OF WORDS TO PHRASES ==================================== When creating a list of words, commas are used between adjacent items, except if the items contain commas, in which case semicolons are used. But if there are less than two items, the commas/semicolons are omitted entirely. The final item also has a conjunction (usually "and" or "or") before it. And although it's technically incorrect (and sometimes misleading), some people prefer to omit the comma before that final conjunction, even when there are more than two items. That's complicated enough to warrant its own method: ``join()``. This method expects a tuple of words, possibly with one or more options. It returns a string that joins the list together in the normal English usage. For example:: print("You chose ", p.join(selected_items)) # You chose barley soup, roast beef, and Yorkshire pudding print("You chose ", p.join(selected_items, final_sep=>"")) # You chose barley soup, roast beef and Yorkshire pudding print("Please chose ", p.join(side_orders, conj=>"or")) # Please chose salad, vegetables, or ice-cream The available options are:: Option named Specifies Default value conj Final conjunction "and" sep Inter-item separator "," last_sep Final separator value of 'sep' option sep_spaced Space follows sep True conj_spaced Spaces around conj True INTERPOLATING INFLECTIONS IN STRINGS ==================================== By far the commonest use of the inflection methods is to produce message strings for various purposes. For example:: print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.") if severity > 1: print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.") Unfortunately the need to separate each method call detracts significantly from the readability of the resulting code. To ameliorate this problem, inflect.py provides a string-interpolating method (``inflect(txt)``), which recognizes calls to the various inflection methods within a string and interpolates them appropriately. Using ``inflect`` the previous example could be rewritten:: print(p.inflect("num({0}) plural_noun(error) plural_verb(was) detected.".format(errors))) if severity > 1: print(p.inflect("plural_adj(This) plural_noun(error) plural_verb(was) fatal.")) Note that ``inflect`` also correctly handles calls to the ``num()`` method (whether interpolated or antecedent). The ``inflect()`` method has a related extra feature, in that it *automatically* cancels any "default number" value before it returns its interpolated string. This means that calls to ``num()`` which are embedded in an ``inflect()``-interpolated string do not "escape" and interfere with subsequent inflections. MODERN VS CLASSICAL INFLECTIONS =============================== Certain words, mainly of Latin or Ancient Greek origin, can form plurals either using the standard English "-s" suffix, or with their original Latin or Greek inflections. For example:: p.plural("stigma") # -> "stigmas" or "stigmata" p.plural("torus") # -> "toruses" or "tori" p.plural("index") # -> "indexes" or "indices" p.plural("millennium") # -> "millenniums" or "millennia" p.plural("ganglion") # -> "ganglions" or "ganglia" p.plural("octopus") # -> "octopuses" or "octopodes" inflect.py caters to such words by providing an "alternate state" of inflection known as "classical mode". By default, words are inflected using their contemporary English plurals, but if classical mode is invoked, the more traditional plural forms are returned instead. The method ``classical()`` controls this feature. If ``classical()`` is called with no arguments, it unconditionally invokes classical mode. If it is called with a single argument, it turns all classical inflects on or off (depending on whether the argument is true or false). If called with two or more arguments, those arguments specify which aspects of classical behaviour are to be used. Thus:: p.classical() # SWITCH ON CLASSICAL MODE print(p.plural("formula") # -> "formulae") p.classical(all=False) # SWITCH OFF CLASSICAL MODE print(p.plural("formula") # -> "formulas") p.classical(cmode=True) # CLASSICAL MODE IFF cmode print(p.plural("formula") # -> "formulae" (IF cmode)) # -> "formulas" (OTHERWISE) p.classical(herd=True) # SWITCH ON CLASSICAL MODE FOR "HERD" NOUNS print(p.plural("wilderbeest") # -> "wilderbeest") p.classical(names=True) # SWITCH ON CLASSICAL MODE FOR NAMES print(p.plural("sally") # -> "sallies") print(p.plural("Sally") # -> "Sallys") Note however that ``classical()`` has no effect on the inflection of words which are now fully assimilated. Hence:: p.plural("forum") # ALWAYS -> "forums" p.plural("criterion") # ALWAYS -> "criteria" LEI assumes that a capitalized word is a person's name. So it forms the plural according to the rules for names (which is that you don't inflect, you just add -s or -es). You can choose to turn that behaviour off (it's on by the default, even when the module isn't in classical mode) by calling `` classical(names=0) `` USER-DEFINED INFLECTIONS ======================== Adding plurals at run-time -------------------------- inflect.py provides five methods which allow the programmer to override the module's behaviour for specific cases: ``defnoun(singular, plural)`` The ``defnoun`` method takes a pair of string arguments: the singular and the plural forms of the noun being specified. The singular form specifies a pattern to be interpolated (as ``m/^(?:$first_arg)$/i``). Any noun matching this pattern is then replaced by the string in the second argument. The second argument specifies a string which is interpolated after the match succeeds, and is then used as the plural form. For example:: defnoun( 'cow' , 'kine') defnoun( '(.+i)o' , '$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!') Note that both arguments should usually be specified in single quotes, so that they are not interpolated when they are specified, but later (when words are compared to them). As indicated by the last example, care also needs to be taken with certain characters in the second argument, to ensure that they are not unintentionally interpolated during comparison. The second argument string may also specify a second variant of the plural form, to be used when "classical" plurals have been requested. The beginning of the second variant is marked by a '|' character:: defnoun( 'cow' , 'cows|kine') defnoun( '(.+i)o' , '$1os|$1i') defnoun( 'spam(mer)?' , '\\$\\%\\@#\\$\\@#!!|varmints') If no classical variant is given, the specified plural form is used in both normal and "classical" modes. .. #TODO: check that the following paragraph is implemented If the second argument is ``None`` instead of a string, then the current user definition for the first argument is removed, and the standard plural inflection(s) restored. Note that in all cases, later plural definitions for a particular singular form replace earlier definitions of the same form. For example:: # FIRST, HIDE THE MODERN FORM.... defnoun( 'aviatrix' , 'aviatrices') # LATER, HIDE THE CLASSICAL FORM... defnoun( 'aviatrix' , 'aviatrixes') # FINALLY, RESTORE THE DEFAULT BEHAVIOUR... defnoun( 'aviatrix' , undef) Special care is also required when defining general patterns and associated specific exceptions: put the more specific cases *after* the general pattern. For example:: defnoun( '(.+)us' , '$1i') # EVERY "-us" TO "-i" defnoun( 'bus' , 'buses') # EXCEPT FOR "bus" This "try-most-recently-defined-first" approach to matching user-defined words is also used by ``defverb``, ``defa`` and ``defan``. ``defverb(s1, p1, s2, p2, s3, p3)`` The ``defverb`` method takes three pairs of string arguments (that is, six arguments in total), specifying the singular and plural forms of the three "persons" of verb. As with ``defnoun``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defverb('am' , 'are', 'are' , 'are|art", 'is' , 'are') defverb('have' , 'have', 'have' , 'have", 'ha(s|th)' , 'have') Note that as with ``defnoun``, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defadj(singular, plural)`` The ``defadj`` method takes a pair of string arguments, which specify the singular and plural forms of the adjective being defined. As with ``defnoun`` and ``defadj``, the singular forms are specifications of run-time-interpolated patterns, whilst the plural forms are specifications of (up to two) run-time-interpolated strings:: defadj( 'this' , 'these') defadj( 'red' , 'red|gules') As previously, modern/classical variants of plurals may be separately specified, subsequent definitions replace previous ones, and ``None``'ed plural forms revert to the standard behaviour. ``defa(pattern)`` and ``defan(pattern)`` The ``defa`` and ``defan`` methods each take a single argument, which specifies a pattern. If a word passed to ``a()`` or ``an()`` matches this pattern, it will be prefixed (unconditionally) with the corresponding indefinite article. For example:: defa( 'error') defa( 'in.+') defan('mistake') defan('error') As with the other ``def_...`` methods, such redefinitions are sequential in effect so that, after the above example, "error" will be inflected with "an". The ``<$HOME/.inflectrc`` file ------------------------------ THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET When it is imported, inflect.py executes (as Perl code) the contents of any file named ``.inflectrc`` which it finds in the in the directory where ``Lingua/EN/Inflect.pm`` is installed, or in the current home directory (``$ENV{HOME}``), or in both. Note that the code is executed within the inflect.py namespace. Hence the user or the local Perl guru can make appropriate calls to ``defnoun``, ``defverb``, etc. in one of these ``.inflectrc`` files, to permanently and universally modify the behaviour of the module. For example > cat /usr/local/lib/perl5/Text/Inflect/.inflectrc defnoun "UNIX" => "UN*X|UNICES" defverb "teco" => "teco", # LITERALLY: "to edit with TECO" "teco" => "teco", "tecos" => "teco" defa "Euler.*"; # "Yewler" TURNS IN HIS GRAVE Note that calls to the ``def_...`` methods from within a program will take precedence over the contents of the home directory F<.inflectrc> file, which in turn takes precedence over the system-wide F<.inflectrc> file. DIAGNOSTICS =========== THIS HAS NOT BEEN IMPLEMENTED IN THE PYTHON VERSION YET On loading, if the Perl code in a ``.inflectrc`` file is invalid (syntactically or otherwise), an appropriate fatal error is issued. A common problem is not ending the file with something that evaluates to true (as the five ``def_...`` methods do). Using the five ``def_...`` methods directly in a program may also result in fatal diagnostics, if a (singular) pattern or an interpolated (plural) string is somehow invalid. Specific diagnostics related to user-defined inflections are: ``"Bad user-defined singular pattern:\t %s"`` The singular form of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb``, ``defadj``, ``defa`` or ``defan``) is not a valid Perl regular expression. The actual Perl error message is also given. ``"Bad user-defined plural string: '%s'"`` The plural form(s) of a user-defined noun or verb (as defined by a call to ``defnoun``, ``defverb`` or ``defadj``) is not a valid Perl interpolated string (usually because it interpolates some undefined variable). ``"Bad .inflectrc file (%s): %s"`` Some other problem occurred in loading the named local or global F<.inflectrc> file. The Perl error message (including the line number) is also given. There are *no* diagnosable run-time error conditions for the actual inflection methods, except ``number_to_words`` and hence no run-time diagnostics. If the inflection methods are unable to form a plural via a user-definition or an inbuilt rule, they just "guess" the commonest English inflection: adding "-s" for nouns, removing "-s" for verbs, and no inflection for adjectives. ``inflect.py`` can raise the following execeptions: ``BadChunkingOptionError`` The optional argument to ``number_to_words()`` wasn't 1, 2 or 3. ``NumOutOfRangeError`` ``number_to_words()`` was passed a number larger than 999,999,999,999,999,999,999,999,999,999,999,999 (that is: nine hundred and ninety-nine decillion, nine hundred and ninety-nine nonillion, nine hundred and ninety-nine octillion, nine hundred and ninety-nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, nine hundred and ninety-nine quadrillion, nine hundred and ninety-nine trillion, nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine :-) The problem is that ``number_to_words`` doesn't know any words for number components bigger than "decillion". .. #TODO expand these ``UnknownClassicalModeError`` ``BadNumValueError`` ``BadUserDefinedPatternError`` ``BadRcFileError`` OTHER ISSUES ============ 2nd Person precedence --------------------- If a verb has identical 1st and 2nd person singular forms, but different 1st and 2nd person plural forms, then when its plural is constructed, the 2nd person plural form is always preferred. The author is not currently aware of any such verbs in English, but is not quite arrogant enough to assume *ipso facto* that none exist. Nominative precedence --------------------- The singular pronoun "it" presents a special problem because its plural form can vary, depending on its "case". For example:: It ate my homework -> They ate my homework It ate it -> They ate them I fed my homework to it -> I fed my homework to them As a consequence of this ambiguity, ``plural()`` or ``plural_noun`` have been implemented so that they always return the *nominative* plural (that is, "they"). However, when asked for the plural of an unambiguously *accusative* "it" (namely, ``plural("to it")``, ``plural_noun("from it")``, ``plural("with it")``, etc.), both methods will correctly return the accusative plural ("to them", "from them", "with them", etc.) The plurality of zero --------------------- The rules governing the choice between:: There were no errors. and :: There was no error. are complex and often depend more on *intent* rather than *content*. Hence it is infeasible to specify such rules algorithmically. Therefore, inflect.py contents itself with the following compromise: If the governing number is zero, inflections always return the plural form unless the appropriate "classical" inflection is in effect, in which case the singular form is always returned. Thus, the sequence:: p.num(0) print(p.inflect("There plural(was) no(choice)")) produces "There were no choices", whereas:: p.classical(zero=True) p.num(0) print(p.inflect("There plural(was) no(choice)")) it will print("There was no choice".) Homographs with heterogeneous plurals ------------------------------------- Another context in which intent (and not content) sometimes determines plurality is where two distinct meanings of a word require different plurals. For example:: Three basses were stolen from the band's equipment trailer. Three bass were stolen from the band's aquarium. I put the mice next to the cheese. I put the mouses next to the computers. Several thoughts about leaving crossed my mind. Several thought about leaving across my lawn. inflect.py handles such words in two ways: - If both meanings of the word are the *same* part of speech (for example, "bass" is a noun in both sentences above), then one meaning is chosen as the "usual" meaning, and only that meaning's plural is ever returned by any of the inflection methods. - If each meaning of the word is a different part of speech (for example, "thought" is both a noun and a verb), then the noun's plural is returned by ``plural()`` and ``plural_noun()`` and the verb's plural is returned only by ``plural_verb()``. Such contexts are, fortunately, uncommon (particularly "same-part-of-speech" examples). An informal study of nearly 600 "difficult plurals" indicates that ``plural()`` can be relied upon to "get it right" about 98% of the time (although, of course, ichthyophilic guitarists or cyber-behaviouralists may experience higher rates of confusion). If the choice of a particular "usual inflection" is considered inappropriate, it can always be reversed with a preliminary call to the corresponding ``def_...`` method. NOTE ==== There will be no further correspondence on: "octopi". Despite the populist pandering of certain New World dictionaries, the plural is "octopuses" or (for the pendantic classicist) "octopodes". The suffix "-pus" is Greek, not Latin, so the plural is "-podes", not "pi". "virus". Had no plural in Latin (possibly because it was a mass noun). The only plural is the Anglicized "viruses". AUTHORS ======= Thorben Krüger (github@benthor.name) * established Python 3 compatibility Paul Dyson (pwdyson@yahoo.com) * converted code from Perl to Python * added singular_noun functionality Original Perl version of the code and documentation: Damian Conway (damian@conway.org), Matthew Persico (ORD inflection) BUGS AND IRRITATIONS ==================== The endless inconsistencies of English. (*Please* report words for which the correct plural or indefinite article is not formed, so that the reliability of inflect.py can be improved.) Keywords: plural,inflect,participle Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Linguistic Provides: inflect Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* inflect-2.1.0/inflect.egg-info/SOURCES.txt0000644000076500000240000000122213372337712020527 0ustar jaracostaff00000000000000.flake8 .gitignore .travis.yml CHANGES.txt CONTRIBUTING.md LICENSE README.rst inflect.py pyproject.toml setup.cfg setup.py tox.ini inflect.egg-info/PKG-INFO inflect.egg-info/SOURCES.txt inflect.egg-info/dependency_links.txt inflect.egg-info/top_level.txt tests/__init__.py tests/inflections.txt tests/test_an.py tests/test_classical_all.py tests/test_classical_ancient.py tests/test_classical_herd.py tests/test_classical_names.py tests/test_classical_person.py tests/test_classical_zero.py tests/test_compounds.py tests/test_inflections.py tests/test_join.py tests/test_numwords.py tests/test_pl_si.py tests/test_pwd.py tests/test_unicode.py tests/words.txtinflect-2.1.0/inflect.egg-info/dependency_links.txt0000644000076500000240000000000113372337712022714 0ustar jaracostaff00000000000000 inflect-2.1.0/inflect.egg-info/top_level.txt0000644000076500000240000000001013372337712021367 0ustar jaracostaff00000000000000inflect inflect-2.1.0/inflect.py0000644000076500000240000027672013372337710015542 0ustar jaracostaff00000000000000""" inflect.py: correctly generate plurals, ordinals, indefinite articles; convert numbers to words Copyright (C) 2010 Paul Dyson Based upon the Perl module Lingua::EN::Inflect by Damian Conway. The original Perl module Lingua::EN::Inflect by Damian Conway is available from http://search.cpan.org/~dconway/ This module can be downloaded at http://pypi.org/project/inflect methods: classical inflect plural plural_noun plural_verb plural_adj singular_noun no num a an compare compare_nouns compare_verbs compare_adjs present_participle ordinal number_to_words join defnoun defverb defadj defa defan INFLECTIONS: classical inflect plural plural_noun plural_verb plural_adj singular_noun compare no num a an present_participle PLURALS: classical inflect plural plural_noun plural_verb plural_adj singular_noun no num compare compare_nouns compare_verbs compare_adjs COMPARISONS: classical compare compare_nouns compare_verbs compare_adjs ARTICLES: classical inflect num a an NUMERICAL: ordinal number_to_words USER_DEFINED: defnoun defverb defadj defa defan Exceptions: UnknownClassicalModeError BadNumValueError BadChunkingOptionError NumOutOfRangeError BadUserDefinedPatternError BadRcFileError BadGenderError """ from __future__ import unicode_literals import ast import sys import re class UnknownClassicalModeError(Exception): pass class BadNumValueError(Exception): pass class BadChunkingOptionError(Exception): pass class NumOutOfRangeError(Exception): pass class BadUserDefinedPatternError(Exception): pass class BadRcFileError(Exception): pass class BadGenderError(Exception): pass __version__ = "2.1.0" STDOUT_ON = False def print3(txt): if STDOUT_ON: print(txt) def enclose(s): return "(?:%s)" % s def joinstem(cutpoint=0, words=""): """ join stem of each word in words into a string for regex each word is truncated at cutpoint cutpoint is usually negative indicating the number of letters to remove from the end of each word e.g. joinstem(-2, ["ephemeris", "iris", ".*itis"]) returns (?:ephemer|ir|.*it) """ return enclose("|".join(w[:cutpoint] for w in words)) def bysize(words): """ take a list of words and return a dict of sets sorted by word length e.g. ret[3]=set(['ant', 'cat', 'dog', 'pig']) ret[4]=set(['frog', 'goat']) ret[5]=set(['horse']) ret[8]=set(['elephant']) """ ret = {} for w in words: if len(w) not in ret: ret[len(w)] = set() ret[len(w)].add(w) return ret def make_pl_si_lists(lst, plending, siendingsize, dojoinstem=True): """ given a list of singular words: lst an ending to append to make the plural: plending the number of characters to remove from the singular before appending plending: siendingsize a flag whether to create a joinstem: dojoinstem return: a list of pluralised words: si_list (called si because this is what you need to look for to make the singular) the pluralised words as a dict of sets sorted by word length: si_bysize the singular words as a dict of sets sorted by word length: pl_bysize if dojoinstem is True: a regular expression that matches any of the stems: stem """ if siendingsize is not None: siendingsize = -siendingsize si_list = [w[:siendingsize] + plending for w in lst] pl_bysize = bysize(lst) si_bysize = bysize(si_list) if dojoinstem: stem = joinstem(siendingsize, lst) return si_list, si_bysize, pl_bysize, stem else: return si_list, si_bysize, pl_bysize # 1. PLURALS pl_sb_irregular_s = { "corpus": "corpuses|corpora", "opus": "opuses|opera", "genus": "genera", "mythos": "mythoi", "penis": "penises|penes", "testis": "testes", "atlas": "atlases|atlantes", "yes": "yeses", } pl_sb_irregular = { "child": "children", "brother": "brothers|brethren", "loaf": "loaves", "hoof": "hoofs|hooves", "beef": "beefs|beeves", "thief": "thiefs|thieves", "money": "monies", "mongoose": "mongooses", "ox": "oxen", "cow": "cows|kine", "graffito": "graffiti", "octopus": "octopuses|octopodes", "genie": "genies|genii", "ganglion": "ganglions|ganglia", "trilby": "trilbys", "turf": "turfs|turves", "numen": "numina", "atman": "atmas", "occiput": "occiputs|occipita", "sabretooth": "sabretooths", "sabertooth": "sabertooths", "lowlife": "lowlifes", "flatfoot": "flatfoots", "tenderfoot": "tenderfoots", "romany": "romanies", "jerry": "jerries", "mary": "maries", "talouse": "talouses", "blouse": "blouses", "rom": "roma", "carmen": "carmina", } pl_sb_irregular.update(pl_sb_irregular_s) # pl_sb_irregular_keys = enclose('|'.join(pl_sb_irregular.keys())) pl_sb_irregular_caps = { "Romany": "Romanies", "Jerry": "Jerrys", "Mary": "Marys", "Rom": "Roma", } pl_sb_irregular_compound = {"prima donna": "prima donnas|prime donne"} si_sb_irregular = {v: k for (k, v) in pl_sb_irregular.items()} keys = list(si_sb_irregular.keys()) for k in keys: if "|" in k: k1, k2 = k.split("|") si_sb_irregular[k1] = si_sb_irregular[k2] = si_sb_irregular[k] del si_sb_irregular[k] si_sb_irregular_caps = {v: k for (k, v) in pl_sb_irregular_caps.items()} si_sb_irregular_compound = {v: k for (k, v) in pl_sb_irregular_compound.items()} keys = list(si_sb_irregular_compound.keys()) for k in keys: if "|" in k: k1, k2 = k.split("|") si_sb_irregular_compound[k1] = si_sb_irregular_compound[ k2 ] = si_sb_irregular_compound[k] del si_sb_irregular_compound[k] # si_sb_irregular_keys = enclose('|'.join(si_sb_irregular.keys())) # Z's that don't double pl_sb_z_zes_list = ("quartz", "topaz") pl_sb_z_zes_bysize = bysize(pl_sb_z_zes_list) pl_sb_ze_zes_list = ("snooze",) pl_sb_ze_zes_bysize = bysize(pl_sb_ze_zes_list) # CLASSICAL "..is" -> "..ides" pl_sb_C_is_ides_complete = [ # GENERAL WORDS... "ephemeris", "iris", "clitoris", "chrysalis", "epididymis", ] pl_sb_C_is_ides_endings = [ # INFLAMATIONS... "itis" ] pl_sb_C_is_ides = joinstem( -2, pl_sb_C_is_ides_complete + [".*%s" % w for w in pl_sb_C_is_ides_endings] ) pl_sb_C_is_ides_list = pl_sb_C_is_ides_complete + pl_sb_C_is_ides_endings ( si_sb_C_is_ides_list, si_sb_C_is_ides_bysize, pl_sb_C_is_ides_bysize, ) = make_pl_si_lists(pl_sb_C_is_ides_list, "ides", 2, dojoinstem=False) # CLASSICAL "..a" -> "..ata" pl_sb_C_a_ata_list = ( "anathema", "bema", "carcinoma", "charisma", "diploma", "dogma", "drama", "edema", "enema", "enigma", "lemma", "lymphoma", "magma", "melisma", "miasma", "oedema", "sarcoma", "schema", "soma", "stigma", "stoma", "trauma", "gumma", "pragma", ) ( si_sb_C_a_ata_list, si_sb_C_a_ata_bysize, pl_sb_C_a_ata_bysize, pl_sb_C_a_ata, ) = make_pl_si_lists(pl_sb_C_a_ata_list, "ata", 1) # UNCONDITIONAL "..a" -> "..ae" pl_sb_U_a_ae_list = ("alumna", "alga", "vertebra", "persona") ( si_sb_U_a_ae_list, si_sb_U_a_ae_bysize, pl_sb_U_a_ae_bysize, pl_sb_U_a_ae, ) = make_pl_si_lists(pl_sb_U_a_ae_list, "e", None) # CLASSICAL "..a" -> "..ae" pl_sb_C_a_ae_list = ( "amoeba", "antenna", "formula", "hyperbola", "medusa", "nebula", "parabola", "abscissa", "hydra", "nova", "lacuna", "aurora", "umbra", "flora", "fauna", ) ( si_sb_C_a_ae_list, si_sb_C_a_ae_bysize, pl_sb_C_a_ae_bysize, pl_sb_C_a_ae, ) = make_pl_si_lists(pl_sb_C_a_ae_list, "e", None) # CLASSICAL "..en" -> "..ina" pl_sb_C_en_ina_list = ("stamen", "foramen", "lumen") ( si_sb_C_en_ina_list, si_sb_C_en_ina_bysize, pl_sb_C_en_ina_bysize, pl_sb_C_en_ina, ) = make_pl_si_lists(pl_sb_C_en_ina_list, "ina", 2) # UNCONDITIONAL "..um" -> "..a" pl_sb_U_um_a_list = ( "bacterium", "agendum", "desideratum", "erratum", "stratum", "datum", "ovum", "extremum", "candelabrum", ) ( si_sb_U_um_a_list, si_sb_U_um_a_bysize, pl_sb_U_um_a_bysize, pl_sb_U_um_a, ) = make_pl_si_lists(pl_sb_U_um_a_list, "a", 2) # CLASSICAL "..um" -> "..a" pl_sb_C_um_a_list = ( "maximum", "minimum", "momentum", "optimum", "quantum", "cranium", "curriculum", "dictum", "phylum", "aquarium", "compendium", "emporium", "enconium", "gymnasium", "honorarium", "interregnum", "lustrum", "memorandum", "millennium", "rostrum", "spectrum", "speculum", "stadium", "trapezium", "ultimatum", "medium", "vacuum", "velum", "consortium", "arboretum", ) ( si_sb_C_um_a_list, si_sb_C_um_a_bysize, pl_sb_C_um_a_bysize, pl_sb_C_um_a, ) = make_pl_si_lists(pl_sb_C_um_a_list, "a", 2) # UNCONDITIONAL "..us" -> "i" pl_sb_U_us_i_list = ( "alumnus", "alveolus", "bacillus", "bronchus", "locus", "nucleus", "stimulus", "meniscus", "sarcophagus", ) ( si_sb_U_us_i_list, si_sb_U_us_i_bysize, pl_sb_U_us_i_bysize, pl_sb_U_us_i, ) = make_pl_si_lists(pl_sb_U_us_i_list, "i", 2) # CLASSICAL "..us" -> "..i" pl_sb_C_us_i_list = ( "focus", "radius", "genius", "incubus", "succubus", "nimbus", "fungus", "nucleolus", "stylus", "torus", "umbilicus", "uterus", "hippopotamus", "cactus", ) ( si_sb_C_us_i_list, si_sb_C_us_i_bysize, pl_sb_C_us_i_bysize, pl_sb_C_us_i, ) = make_pl_si_lists(pl_sb_C_us_i_list, "i", 2) # CLASSICAL "..us" -> "..us" (ASSIMILATED 4TH DECLENSION LATIN NOUNS) pl_sb_C_us_us = ( "status", "apparatus", "prospectus", "sinus", "hiatus", "impetus", "plexus", ) pl_sb_C_us_us_bysize = bysize(pl_sb_C_us_us) # UNCONDITIONAL "..on" -> "a" pl_sb_U_on_a_list = ( "criterion", "perihelion", "aphelion", "phenomenon", "prolegomenon", "noumenon", "organon", "asyndeton", "hyperbaton", ) ( si_sb_U_on_a_list, si_sb_U_on_a_bysize, pl_sb_U_on_a_bysize, pl_sb_U_on_a, ) = make_pl_si_lists(pl_sb_U_on_a_list, "a", 2) # CLASSICAL "..on" -> "..a" pl_sb_C_on_a_list = ("oxymoron",) ( si_sb_C_on_a_list, si_sb_C_on_a_bysize, pl_sb_C_on_a_bysize, pl_sb_C_on_a, ) = make_pl_si_lists(pl_sb_C_on_a_list, "a", 2) # CLASSICAL "..o" -> "..i" (BUT NORMALLY -> "..os") pl_sb_C_o_i = [ "solo", "soprano", "basso", "alto", "contralto", "tempo", "piano", "virtuoso", ] # list not tuple so can concat for pl_sb_U_o_os pl_sb_C_o_i_bysize = bysize(pl_sb_C_o_i) si_sb_C_o_i_bysize = bysize(["%si" % w[:-1] for w in pl_sb_C_o_i]) pl_sb_C_o_i_stems = joinstem(-1, pl_sb_C_o_i) # ALWAYS "..o" -> "..os" pl_sb_U_o_os_complete = {"ado", "ISO", "NATO", "NCO", "NGO", "oto"} si_sb_U_o_os_complete = {"%ss" % w for w in pl_sb_U_o_os_complete} pl_sb_U_o_os_endings = [ "aficionado", "aggro", "albino", "allegro", "ammo", "Antananarivo", "archipelago", "armadillo", "auto", "avocado", "Bamako", "Barquisimeto", "bimbo", "bingo", "Biro", "bolero", "Bolzano", "bongo", "Boto", "burro", "Cairo", "canto", "cappuccino", "casino", "cello", "Chicago", "Chimango", "cilantro", "cochito", "coco", "Colombo", "Colorado", "commando", "concertino", "contango", "credo", "crescendo", "cyano", "demo", "ditto", "Draco", "dynamo", "embryo", "Esperanto", "espresso", "euro", "falsetto", "Faro", "fiasco", "Filipino", "flamenco", "furioso", "generalissimo", "Gestapo", "ghetto", "gigolo", "gizmo", "Greensboro", "gringo", "Guaiabero", "guano", "gumbo", "gyro", "hairdo", "hippo", "Idaho", "impetigo", "inferno", "info", "intermezzo", "intertrigo", "Iquico", "jumbo", "junto", "Kakapo", "kilo", "Kinkimavo", "Kokako", "Kosovo", "Lesotho", "libero", "libido", "libretto", "lido", "Lilo", "limbo", "limo", "lineno", "lingo", "lino", "livedo", "loco", "logo", "lumbago", "macho", "macro", "mafioso", "magneto", "magnifico", "Majuro", "Malabo", "manifesto", "Maputo", "Maracaibo", "medico", "memo", "metro", "Mexico", "micro", "Milano", "Monaco", "mono", "Montenegro", "Morocco", "Muqdisho", "myo", "neutrino", "Ningbo", "octavo", "oregano", "Orinoco", "Orlando", "Oslo", "panto", "Paramaribo", "Pardusco", "pedalo", "photo", "pimento", "pinto", "pleco", "Pluto", "pogo", "polo", "poncho", "Porto-Novo", "Porto", "pro", "psycho", "pueblo", "quarto", "Quito", "rhino", "risotto", "rococo", "rondo", "Sacramento", "saddo", "sago", "salvo", "Santiago", "Sapporo", "Sarajevo", "scherzando", "scherzo", "silo", "sirocco", "sombrero", "staccato", "sterno", "stucco", "stylo", "sumo", "Taiko", "techno", "terrazzo", "testudo", "timpano", "tiro", "tobacco", "Togo", "Tokyo", "torero", "Torino", "Toronto", "torso", "tremolo", "typo", "tyro", "ufo", "UNESCO", "vaquero", "vermicello", "verso", "vibrato", "violoncello", "Virgo", "weirdo", "WHO", "WTO", "Yamoussoukro", "yo-yo", "zero", "Zibo", ] + pl_sb_C_o_i pl_sb_U_o_os_bysize = bysize(pl_sb_U_o_os_endings) si_sb_U_o_os_bysize = bysize(["%ss" % w for w in pl_sb_U_o_os_endings]) # UNCONDITIONAL "..ch" -> "..chs" pl_sb_U_ch_chs_list = ("czech", "eunuch", "stomach") ( si_sb_U_ch_chs_list, si_sb_U_ch_chs_bysize, pl_sb_U_ch_chs_bysize, pl_sb_U_ch_chs, ) = make_pl_si_lists(pl_sb_U_ch_chs_list, "s", None) # UNCONDITIONAL "..[ei]x" -> "..ices" pl_sb_U_ex_ices_list = ("codex", "murex", "silex") ( si_sb_U_ex_ices_list, si_sb_U_ex_ices_bysize, pl_sb_U_ex_ices_bysize, pl_sb_U_ex_ices, ) = make_pl_si_lists(pl_sb_U_ex_ices_list, "ices", 2) pl_sb_U_ix_ices_list = ("radix", "helix") ( si_sb_U_ix_ices_list, si_sb_U_ix_ices_bysize, pl_sb_U_ix_ices_bysize, pl_sb_U_ix_ices, ) = make_pl_si_lists(pl_sb_U_ix_ices_list, "ices", 2) # CLASSICAL "..[ei]x" -> "..ices" pl_sb_C_ex_ices_list = ( "vortex", "vertex", "cortex", "latex", "pontifex", "apex", "index", "simplex", ) ( si_sb_C_ex_ices_list, si_sb_C_ex_ices_bysize, pl_sb_C_ex_ices_bysize, pl_sb_C_ex_ices, ) = make_pl_si_lists(pl_sb_C_ex_ices_list, "ices", 2) pl_sb_C_ix_ices_list = ("appendix",) ( si_sb_C_ix_ices_list, si_sb_C_ix_ices_bysize, pl_sb_C_ix_ices_bysize, pl_sb_C_ix_ices, ) = make_pl_si_lists(pl_sb_C_ix_ices_list, "ices", 2) # ARABIC: ".." -> "..i" pl_sb_C_i_list = ("afrit", "afreet", "efreet") (si_sb_C_i_list, si_sb_C_i_bysize, pl_sb_C_i_bysize, pl_sb_C_i) = make_pl_si_lists( pl_sb_C_i_list, "i", None ) # HEBREW: ".." -> "..im" pl_sb_C_im_list = ("goy", "seraph", "cherub") (si_sb_C_im_list, si_sb_C_im_bysize, pl_sb_C_im_bysize, pl_sb_C_im) = make_pl_si_lists( pl_sb_C_im_list, "im", None ) # UNCONDITIONAL "..man" -> "..mans" pl_sb_U_man_mans_list = """ ataman caiman cayman ceriman desman dolman farman harman hetman human leman ottoman shaman talisman """.split() pl_sb_U_man_mans_caps_list = """ Alabaman Bahaman Burman German Hiroshiman Liman Nakayaman Norman Oklahoman Panaman Roman Selman Sonaman Tacoman Yakiman Yokohaman Yuman """.split() ( si_sb_U_man_mans_list, si_sb_U_man_mans_bysize, pl_sb_U_man_mans_bysize, ) = make_pl_si_lists(pl_sb_U_man_mans_list, "s", None, dojoinstem=False) ( si_sb_U_man_mans_caps_list, si_sb_U_man_mans_caps_bysize, pl_sb_U_man_mans_caps_bysize, ) = make_pl_si_lists(pl_sb_U_man_mans_caps_list, "s", None, dojoinstem=False) pl_sb_uninflected_s_complete = [ # PAIRS OR GROUPS SUBSUMED TO A SINGULAR... "breeches", "britches", "pajamas", "pyjamas", "clippers", "gallows", "hijinks", "headquarters", "pliers", "scissors", "testes", "herpes", "pincers", "shears", "proceedings", "trousers", # UNASSIMILATED LATIN 4th DECLENSION "cantus", "coitus", "nexus", # RECENT IMPORTS... "contretemps", "corps", "debris", "siemens", # DISEASES "mumps", # MISCELLANEOUS OTHERS... "diabetes", "jackanapes", "series", "species", "subspecies", "rabies", "chassis", "innings", "news", "mews", "haggis", ] pl_sb_uninflected_s_endings = [ # RECENT IMPORTS... "ois", # DISEASES "measles", ] pl_sb_uninflected_s = pl_sb_uninflected_s_complete + [ ".*%s" % w for w in pl_sb_uninflected_s_endings ] pl_sb_uninflected_herd = ( # DON'T INFLECT IN CLASSICAL MODE, OTHERWISE NORMAL INFLECTION "wildebeest", "swine", "eland", "bison", "buffalo", "elk", "rhinoceros", "zucchini", "caribou", "dace", "grouse", "guinea fowl", "guinea-fowl", "haddock", "hake", "halibut", "herring", "mackerel", "pickerel", "pike", "roe", "seed", "shad", "snipe", "teal", "turbot", "water fowl", "water-fowl", ) pl_sb_uninflected_complete = [ # SOME FISH AND HERD ANIMALS "tuna", "salmon", "mackerel", "trout", "bream", "sea-bass", "sea bass", "carp", "cod", "flounder", "whiting", "moose", # OTHER ODDITIES "graffiti", "djinn", "samuri", "offspring", "pence", "quid", "hertz", ] + pl_sb_uninflected_s_complete # SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) pl_sb_uninflected_caps = [ # ALL NATIONALS ENDING IN -ese "Portuguese", "Amoyese", "Borghese", "Congoese", "Faroese", "Foochowese", "Genevese", "Genoese", "Gilbertese", "Hottentotese", "Kiplingese", "Kongoese", "Lucchese", "Maltese", "Nankingese", "Niasese", "Pekingese", "Piedmontese", "Pistoiese", "Sarawakese", "Shavese", "Vermontese", "Wenchowese", "Yengeese", ] pl_sb_uninflected_endings = [ # SOME FISH AND HERD ANIMALS "fish", "deer", "sheep", # ALL NATIONALS ENDING IN -ese "nese", "rese", "lese", "mese", # DISEASES "pox", # OTHER ODDITIES "craft", ] + pl_sb_uninflected_s_endings # SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) pl_sb_uninflected_bysize = bysize(pl_sb_uninflected_endings) # SINGULAR WORDS ENDING IN ...s (ALL INFLECT WITH ...es) pl_sb_singular_s_complete = [ "acropolis", "aegis", "alias", "asbestos", "bathos", "bias", "bronchitis", "bursitis", "caddis", "cannabis", "canvas", "chaos", "cosmos", "dais", "digitalis", "epidermis", "ethos", "eyas", "gas", "glottis", "hubris", "ibis", "lens", "mantis", "marquis", "metropolis", "pathos", "pelvis", "polis", "rhinoceros", "sassafras", "trellis", ] + pl_sb_C_is_ides_complete pl_sb_singular_s_endings = ["ss", "us"] + pl_sb_C_is_ides_endings pl_sb_singular_s_bysize = bysize(pl_sb_singular_s_endings) si_sb_singular_s_complete = ["%ses" % w for w in pl_sb_singular_s_complete] si_sb_singular_s_endings = ["%ses" % w for w in pl_sb_singular_s_endings] si_sb_singular_s_bysize = bysize(si_sb_singular_s_endings) pl_sb_singular_s_es = ["[A-Z].*es"] pl_sb_singular_s = enclose( "|".join( pl_sb_singular_s_complete + [".*%s" % w for w in pl_sb_singular_s_endings] + pl_sb_singular_s_es ) ) # PLURALS ENDING IN uses -> use si_sb_ois_oi_case = ("Bolshois", "Hanois") si_sb_uses_use_case = ("Betelgeuses", "Duses", "Meuses", "Syracuses", "Toulouses") si_sb_uses_use = ( "abuses", "applauses", "blouses", "carouses", "causes", "chartreuses", "clauses", "contuses", "douses", "excuses", "fuses", "grouses", "hypotenuses", "masseuses", "menopauses", "misuses", "muses", "overuses", "pauses", "peruses", "profuses", "recluses", "reuses", "ruses", "souses", "spouses", "suffuses", "transfuses", "uses", ) si_sb_ies_ie_case = ( "Addies", "Aggies", "Allies", "Amies", "Angies", "Annies", "Annmaries", "Archies", "Arties", "Aussies", "Barbies", "Barries", "Basies", "Bennies", "Bernies", "Berties", "Bessies", "Betties", "Billies", "Blondies", "Bobbies", "Bonnies", "Bowies", "Brandies", "Bries", "Brownies", "Callies", "Carnegies", "Carries", "Cassies", "Charlies", "Cheries", "Christies", "Connies", "Curies", "Dannies", "Debbies", "Dixies", "Dollies", "Donnies", "Drambuies", "Eddies", "Effies", "Ellies", "Elsies", "Eries", "Ernies", "Essies", "Eugenies", "Fannies", "Flossies", "Frankies", "Freddies", "Gillespies", "Goldies", "Gracies", "Guthries", "Hallies", "Hatties", "Hetties", "Hollies", "Jackies", "Jamies", "Janies", "Jannies", "Jeanies", "Jeannies", "Jennies", "Jessies", "Jimmies", "Jodies", "Johnies", "Johnnies", "Josies", "Julies", "Kalgoorlies", "Kathies", "Katies", "Kellies", "Kewpies", "Kristies", "Laramies", "Lassies", "Lauries", "Leslies", "Lessies", "Lillies", "Lizzies", "Lonnies", "Lories", "Lorries", "Lotties", "Louies", "Mackenzies", "Maggies", "Maisies", "Mamies", "Marcies", "Margies", "Maries", "Marjories", "Matties", "McKenzies", "Melanies", "Mickies", "Millies", "Minnies", "Mollies", "Mounties", "Nannies", "Natalies", "Nellies", "Netties", "Ollies", "Ozzies", "Pearlies", "Pottawatomies", "Reggies", "Richies", "Rickies", "Robbies", "Ronnies", "Rosalies", "Rosemaries", "Rosies", "Roxies", "Rushdies", "Ruthies", "Sadies", "Sallies", "Sammies", "Scotties", "Selassies", "Sherries", "Sophies", "Stacies", "Stefanies", "Stephanies", "Stevies", "Susies", "Sylvies", "Tammies", "Terries", "Tessies", "Tommies", "Tracies", "Trekkies", "Valaries", "Valeries", "Valkyries", "Vickies", "Virgies", "Willies", "Winnies", "Wylies", "Yorkies", ) si_sb_ies_ie = ( "aeries", "baggies", "belies", "biggies", "birdies", "bogies", "bonnies", "boogies", "bookies", "bourgeoisies", "brownies", "budgies", "caddies", "calories", "camaraderies", "cockamamies", "collies", "cookies", "coolies", "cooties", "coteries", "crappies", "curies", "cutesies", "dogies", "eyrie", "floozies", "footsies", "freebies", "genies", "goalies", "groupies", "hies", "jalousies", "junkies", "kiddies", "laddies", "lassies", "lies", "lingeries", "magpies", "menageries", "mommies", "movies", "neckties", "newbies", "nighties", "oldies", "organdies", "overlies", "pies", "pinkies", "pixies", "potpies", "prairies", "quickies", "reveries", "rookies", "rotisseries", "softies", "sorties", "species", "stymies", "sweeties", "ties", "underlies", "unties", "veggies", "vies", "yuppies", "zombies", ) si_sb_oes_oe_case = ( "Chloes", "Crusoes", "Defoes", "Faeroes", "Ivanhoes", "Joes", "McEnroes", "Moes", "Monroes", "Noes", "Poes", "Roscoes", "Tahoes", "Tippecanoes", "Zoes", ) si_sb_oes_oe = ( "aloes", "backhoes", "canoes", "does", "floes", "foes", "hoes", "mistletoes", "oboes", "pekoes", "roes", "sloes", "throes", "tiptoes", "toes", "woes", ) si_sb_z_zes = ("quartzes", "topazes") si_sb_zzes_zz = ("buzzes", "fizzes", "frizzes", "razzes") si_sb_ches_che_case = ( "Andromaches", "Apaches", "Blanches", "Comanches", "Nietzsches", "Porsches", "Roches", ) si_sb_ches_che = ( "aches", "avalanches", "backaches", "bellyaches", "caches", "cloches", "creches", "douches", "earaches", "fiches", "headaches", "heartaches", "microfiches", "niches", "pastiches", "psyches", "quiches", "stomachaches", "toothaches", ) si_sb_xes_xe = ("annexes", "axes", "deluxes", "pickaxes") si_sb_sses_sse_case = ("Hesses", "Jesses", "Larousses", "Matisses") si_sb_sses_sse = ( "bouillabaisses", "crevasses", "demitasses", "impasses", "mousses", "posses", ) si_sb_ves_ve_case = ( # *[nwl]ives -> [nwl]live "Clives", "Palmolives", ) si_sb_ves_ve = ( # *[^d]eaves -> eave "interweaves", "weaves", # *[nwl]ives -> [nwl]live "olives", # *[eoa]lves -> [eoa]lve "bivalves", "dissolves", "resolves", "salves", "twelves", "valves", ) plverb_special_s = enclose( "|".join( [pl_sb_singular_s] + pl_sb_uninflected_s + list(pl_sb_irregular_s.keys()) + ["(.*[csx])is", "(.*)ceps", "[A-Z].*s"] ) ) pl_sb_postfix_adj = { "general": [r"(?!major|lieutenant|brigadier|adjutant|.*star)\S+"], "martial": ["court"], "force": ["pound"], } for k in list(pl_sb_postfix_adj.keys()): pl_sb_postfix_adj[k] = enclose( enclose("|".join(pl_sb_postfix_adj[k])) + "(?=(?:-|\\s+)%s)" % k ) pl_sb_postfix_adj_stems = "(" + "|".join(list(pl_sb_postfix_adj.values())) + ")(.*)" # PLURAL WORDS ENDING IS es GO TO SINGULAR is si_sb_es_is = ( "amanuenses", "amniocenteses", "analyses", "antitheses", "apotheoses", "arterioscleroses", "atheroscleroses", "axes", # 'bases', # bases -> basis "catalyses", "catharses", "chasses", "cirrhoses", "cocces", "crises", "diagnoses", "dialyses", "diereses", "electrolyses", "emphases", "exegeses", "geneses", "halitoses", "hydrolyses", "hypnoses", "hypotheses", "hystereses", "metamorphoses", "metastases", "misdiagnoses", "mitoses", "mononucleoses", "narcoses", "necroses", "nemeses", "neuroses", "oases", "osmoses", "osteoporoses", "paralyses", "parentheses", "parthenogeneses", "periphrases", "photosyntheses", "probosces", "prognoses", "prophylaxes", "prostheses", "preces", "psoriases", "psychoanalyses", "psychokineses", "psychoses", "scleroses", "scolioses", "sepses", "silicoses", "symbioses", "synopses", "syntheses", "taxes", "telekineses", "theses", "thromboses", "tuberculoses", "urinalyses", ) pl_prep_list = """ about above across after among around at athwart before behind below beneath beside besides between betwixt beyond but by during except for from in into near of off on onto out over since till to under until unto upon with""".split() pl_prep_list_da = pl_prep_list + ["de", "du", "da"] pl_prep_bysize = bysize(pl_prep_list_da) pl_prep = enclose("|".join(pl_prep_list_da)) pl_sb_prep_dual_compound = ( r"(.*?)((?:-|\s+)(?:" + pl_prep + r")(?:-|\s+))a(?:-|\s+)(.*)" ) singular_pronoun_genders = { "neuter", "feminine", "masculine", "gender-neutral", "feminine or masculine", "masculine or feminine", } pl_pron_nom = { # NOMINATIVE REFLEXIVE "i": "we", "myself": "ourselves", "you": "you", "yourself": "yourselves", "she": "they", "herself": "themselves", "he": "they", "himself": "themselves", "it": "they", "itself": "themselves", "they": "they", "themself": "themselves", # POSSESSIVE "mine": "ours", "yours": "yours", "hers": "theirs", "his": "theirs", "its": "theirs", "theirs": "theirs", } si_pron = {} si_pron["nom"] = {v: k for (k, v) in pl_pron_nom.items()} si_pron["nom"]["we"] = "I" pl_pron_acc = { # ACCUSATIVE REFLEXIVE "me": "us", "myself": "ourselves", "you": "you", "yourself": "yourselves", "her": "them", "herself": "themselves", "him": "them", "himself": "themselves", "it": "them", "itself": "themselves", "them": "them", "themself": "themselves", } pl_pron_acc_keys = enclose("|".join(list(pl_pron_acc.keys()))) pl_pron_acc_keys_bysize = bysize(list(pl_pron_acc.keys())) si_pron["acc"] = {v: k for (k, v) in pl_pron_acc.items()} for thecase, plur, gend, sing in ( ("nom", "they", "neuter", "it"), ("nom", "they", "feminine", "she"), ("nom", "they", "masculine", "he"), ("nom", "they", "gender-neutral", "they"), ("nom", "they", "feminine or masculine", "she or he"), ("nom", "they", "masculine or feminine", "he or she"), ("nom", "themselves", "neuter", "itself"), ("nom", "themselves", "feminine", "herself"), ("nom", "themselves", "masculine", "himself"), ("nom", "themselves", "gender-neutral", "themself"), ("nom", "themselves", "feminine or masculine", "herself or himself"), ("nom", "themselves", "masculine or feminine", "himself or herself"), ("nom", "theirs", "neuter", "its"), ("nom", "theirs", "feminine", "hers"), ("nom", "theirs", "masculine", "his"), ("nom", "theirs", "gender-neutral", "theirs"), ("nom", "theirs", "feminine or masculine", "hers or his"), ("nom", "theirs", "masculine or feminine", "his or hers"), ("acc", "them", "neuter", "it"), ("acc", "them", "feminine", "her"), ("acc", "them", "masculine", "him"), ("acc", "them", "gender-neutral", "them"), ("acc", "them", "feminine or masculine", "her or him"), ("acc", "them", "masculine or feminine", "him or her"), ("acc", "themselves", "neuter", "itself"), ("acc", "themselves", "feminine", "herself"), ("acc", "themselves", "masculine", "himself"), ("acc", "themselves", "gender-neutral", "themself"), ("acc", "themselves", "feminine or masculine", "herself or himself"), ("acc", "themselves", "masculine or feminine", "himself or herself"), ): try: si_pron[thecase][plur][gend] = sing except TypeError: si_pron[thecase][plur] = {} si_pron[thecase][plur][gend] = sing si_pron_acc_keys = enclose("|".join(list(si_pron["acc"].keys()))) si_pron_acc_keys_bysize = bysize(list(si_pron["acc"].keys())) def get_si_pron(thecase, word, gender): try: sing = si_pron[thecase][word] except KeyError: raise # not a pronoun try: return sing[gender] # has several types due to gender except TypeError: return sing # answer independent of gender plverb_irregular_pres = { # 1st PERS. SING. 2ND PERS. SING. 3RD PERS. SINGULAR # 3RD PERS. (INDET.) "am": "are", "are": "are", "is": "are", "was": "were", "were": "were", "was": "were", "have": "have", "have": "have", "has": "have", "do": "do", "do": "do", "does": "do", } plverb_ambiguous_pres = { # 1st PERS. SING. 2ND PERS. SING. 3RD PERS. SINGULAR # 3RD PERS. (INDET.) "act": "act", "act": "act", "acts": "act", "blame": "blame", "blame": "blame", "blames": "blame", "can": "can", "can": "can", "can": "can", "must": "must", "must": "must", "must": "must", "fly": "fly", "fly": "fly", "flies": "fly", "copy": "copy", "copy": "copy", "copies": "copy", "drink": "drink", "drink": "drink", "drinks": "drink", "fight": "fight", "fight": "fight", "fights": "fight", "fire": "fire", "fire": "fire", "fires": "fire", "like": "like", "like": "like", "likes": "like", "look": "look", "look": "look", "looks": "look", "make": "make", "make": "make", "makes": "make", "reach": "reach", "reach": "reach", "reaches": "reach", "run": "run", "run": "run", "runs": "run", "sink": "sink", "sink": "sink", "sinks": "sink", "sleep": "sleep", "sleep": "sleep", "sleeps": "sleep", "view": "view", "view": "view", "views": "view", } plverb_ambiguous_pres_keys = enclose("|".join(list(plverb_ambiguous_pres.keys()))) plverb_irregular_non_pres = ( "did", "had", "ate", "made", "put", "spent", "fought", "sank", "gave", "sought", "shall", "could", "ought", "should", ) plverb_ambiguous_non_pres = enclose( "|".join(("thought", "saw", "bent", "will", "might", "cut")) ) # "..oes" -> "..oe" (the rest are "..oes" -> "o") pl_v_oes_oe = ("canoes", "floes", "oboes", "roes", "throes", "woes") pl_v_oes_oe_endings_size4 = ("hoes", "toes") pl_v_oes_oe_endings_size5 = ("shoes",) pl_count_zero = ("0", "no", "zero", "nil") pl_count_one = ("1", "a", "an", "one", "each", "every", "this", "that") pl_adj_special = {"a": "some", "an": "some", "this": "these", "that": "those"} pl_adj_special_keys = enclose("|".join(list(pl_adj_special.keys()))) pl_adj_poss = { "my": "our", "your": "your", "its": "their", "her": "their", "his": "their", "their": "their", } pl_adj_poss_keys = enclose("|".join(list(pl_adj_poss.keys()))) # 2. INDEFINITE ARTICLES # THIS PATTERN MATCHES STRINGS OF CAPITALS STARTING WITH A "VOWEL-SOUND" # CONSONANT FOLLOWED BY ANOTHER CONSONANT, AND WHICH ARE NOT LIKELY # TO BE REAL WORDS (OH, ALL RIGHT THEN, IT'S JUST MAGIC!) A_abbrev = r""" (?! FJO | [HLMNS]Y. | RY[EO] | SQU | ( F[LR]? | [HL] | MN? | N | RH? | S[CHKLMNPTVW]? | X(YL)?) [AEIOU]) [FHLMNRSX][A-Z] """ # THIS PATTERN CODES THE BEGINNINGS OF ALL ENGLISH WORDS BEGINING WITH A # 'y' FOLLOWED BY A CONSONANT. ANY OTHER Y-CONSONANT PREFIX THEREFORE # IMPLIES AN ABBREVIATION. A_y_cons = "y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt)" # EXCEPTIONS TO EXCEPTIONS A_explicit_a = enclose("|".join(("unabomber", "unanimous", "US"))) A_explicit_an = enclose( "|".join(("euler", "hour(?!i)", "heir", "honest", "hono[ur]", "mpeg")) ) A_ordinal_an = enclose("|".join(("[aefhilmnorsx]-?th",))) A_ordinal_a = enclose("|".join(("[bcdgjkpqtuvwyz]-?th",))) # NUMERICAL INFLECTIONS nth = { 0: "th", 1: "st", 2: "nd", 3: "rd", 4: "th", 5: "th", 6: "th", 7: "th", 8: "th", 9: "th", 11: "th", 12: "th", 13: "th", } ordinal = dict( ty="tieth", one="first", two="second", three="third", five="fifth", eight="eighth", nine="ninth", twelve="twelfth", ) ordinal_suff = "|".join(list(ordinal.keys())) # NUMBERS unit = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] teen = [ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] ten = [ "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", ] mill = [ " ", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion", " sextillion", " septillion", " octillion", " nonillion", " decillion", ] # SUPPORT CLASSICAL PLURALIZATIONS def_classical = dict( all=False, zero=False, herd=False, names=True, persons=False, ancient=False ) all_classical = {k: True for k in list(def_classical.keys())} no_classical = {k: False for k in list(def_classical.keys())} # Maps strings to built-in constant types string_to_constant = {"True": True, "False": False, "None": None} class engine: def __init__(self): self.classical_dict = def_classical.copy() self.persistent_count = None self.mill_count = 0 self.pl_sb_user_defined = [] self.pl_v_user_defined = [] self.pl_adj_user_defined = [] self.si_sb_user_defined = [] self.A_a_user_defined = [] self.thegender = "neuter" deprecated_methods = dict( pl="plural", plnoun="plural_noun", plverb="plural_verb", pladj="plural_adj", sinoun="single_noun", prespart="present_participle", numwords="number_to_words", plequal="compare", plnounequal="compare_nouns", plverbequal="compare_verbs", pladjequal="compare_adjs", wordlist="join", ) def __getattr__(self, meth): if meth in self.deprecated_methods: print3( "{}() deprecated, use {}()".format(meth, self.deprecated_methods[meth]) ) raise DeprecationWarning raise AttributeError def defnoun(self, singular, plural): """ Set the noun plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_sb_user_defined.extend((singular, plural)) self.si_sb_user_defined.extend((plural, singular)) return 1 def defverb(self, s1, p1, s2, p2, s3, p3): """ Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. """ self.checkpat(s1) self.checkpat(s2) self.checkpat(s3) self.checkpatplural(p1) self.checkpatplural(p2) self.checkpatplural(p3) self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3)) return 1 def defadj(self, singular, plural): """ Set the adjective plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_adj_user_defined.extend((singular, plural)) return 1 def defa(self, pattern): """ Define the indefinate article as 'a' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "a")) return 1 def defan(self, pattern): """ Define the indefinate article as 'an' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "an")) return 1 def checkpat(self, pattern): """ check for errors in a regex pattern """ if pattern is None: return try: re.match(pattern, "") except re.error: print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern) raise BadUserDefinedPatternError def checkpatplural(self, pattern): """ check for errors in a regex replace pattern """ return def ud_match(self, word, wordlist): for i in range(len(wordlist) - 2, -2, -2): # backwards through even elements mo = re.search(r"^%s$" % wordlist[i], word, re.IGNORECASE) if mo: if wordlist[i + 1] is None: return None pl = re.sub( r"\$(\d+)", r"\\1", wordlist[i + 1] ) # change $n to \n for expand return mo.expand(pl) return None def classical(self, **kwargs): """ turn classical mode on and off for various categories turn on all classical modes: classical() classical(all=True) turn on or off specific claassical modes: e.g. classical(herd=True) classical(names=False) By default all classical modes are off except names. unknown value in args or key in kwargs rasies exception: UnknownClasicalModeError """ classical_mode = list(def_classical.keys()) if not kwargs: self.classical_dict = all_classical.copy() return if "all" in kwargs: if kwargs["all"]: self.classical_dict = all_classical.copy() else: self.classical_dict = no_classical.copy() for k, v in list(kwargs.items()): if k in classical_mode: self.classical_dict[k] = v else: raise UnknownClassicalModeError def num(self, count=None, show=None): # (;$count,$show) """ Set the number to be used in other method calls. Returns count. Set show to False to return '' instead. """ if count is not None: try: self.persistent_count = int(count) except ValueError: raise BadNumValueError if (show is None) or show: return str(count) else: self.persistent_count = None return "" def gender(self, gender): """ set the gender for the singular of plural pronouns can be one of: 'neuter' ('they' -> 'it') 'feminine' ('they' -> 'she') 'masculine' ('they' -> 'he') 'gender-neutral' ('they' -> 'they') 'feminine or masculine' ('they' -> 'she or he') 'masculine or feminine' ('they' -> 'he or she') """ if gender in singular_pronoun_genders: self.thegender = gender else: raise BadGenderError def _get_value_from_ast(self, obj): """ Return the value of the ast object. """ if isinstance(obj, ast.Num): return obj.n elif isinstance(obj, ast.Str): return obj.s elif isinstance(obj, ast.List): return [self._get_value_from_ast(e) for e in obj.elts] elif isinstance(obj, ast.Tuple): return tuple([self._get_value_from_ast(e) for e in obj.elts]) # None, True and False are NameConstants in Py3.4 and above. elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant): return obj.value # For python versions below 3.4 elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]): return string_to_constant[obj.id] # Probably passed a variable name. # Or passed a single word without wrapping it in quotes as an argument # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") raise NameError("name '%s' is not defined" % obj.id) def _string_to_substitute(self, mo, methods_dict): """ Return the string to be substituted for the match. """ matched_text, f_name = mo.groups() # matched_text is the complete match string. e.g. plural_noun(cat) # f_name is the function name. e.g. plural_noun # Return matched_text if function name is not in methods_dict if f_name not in methods_dict: return matched_text # Parse the matched text a_tree = ast.parse(matched_text) # get the args and kwargs from ast objects args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args] kwargs_list = { kw.arg: self._get_value_from_ast(kw.value) for kw in a_tree.body[0].value.keywords } # Call the corresponding function return methods_dict[f_name](*args_list, **kwargs_list) # 0. PERFORM GENERAL INFLECTIONS IN A STRING def inflect(self, text): """ Perform inflections in a string. e.g. inflect('The plural of cat is plural(cat)') returns 'The plural of cat is cats' can use plural, plural_noun, plural_verb, plural_adj, singular_noun, a, an, no, ordinal, number_to_words, and prespart """ save_persistent_count = self.persistent_count # Dictionary of allowed methods methods_dict = { "plural": self.plural, "plural_adj": self.plural_adj, "plural_noun": self.plural_noun, "plural_verb": self.plural_verb, "singular_noun": self.singular_noun, "a": self.a, "an": self.a, "no": self.no, "ordinal": self.ordinal, "number_to_words": self.number_to_words, "present_participle": self.present_participle, "num": self.num, } # Regular expression to find Python's function call syntax functions_re = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE) output = functions_re.sub( lambda mo: self._string_to_substitute(mo, methods_dict), text ) self.persistent_count = save_persistent_count return output # ## PLURAL SUBROUTINES def postprocess(self, orig, inflected): if "|" in inflected: inflected = inflected.split("|")[self.classical_dict["all"]] result = inflected.split(" ") # Try to fix word wise capitalization for index, word in enumerate(orig.split(" ")): if word == "I": # Is this the only word for exceptions like this # Where the original is fully capitalized # without 'meaning' capitalization? # Also this fails to handle a capitalizaion in context continue if word.capitalize() == word: result[index] = result[index].capitalize() if word == word.upper(): result[index] = result[index].upper() return " ".join(result) def partition_word(self, text): mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text) try: return mo.group(1), mo.group(2), mo.group(3) except AttributeError: # empty string return "", "", "" def plural(self, text, count=None): """ Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_adjective(word, count) or self._pl_special_verb(word, count) or self._plnoun(word, count), ) return "{}{}{}".format(pre, plural, post) def plural_noun(self, text, count=None): """ Return the plural of text, where text is a noun. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._plnoun(word, count)) return "{}{}{}".format(pre, plural, post) def plural_verb(self, text, count=None): """ Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_verb(word, count) or self._pl_general_verb(word, count), ) return "{}{}{}".format(pre, plural, post) def plural_adj(self, text, count=None): """ Return the plural of text, where text is an adjective. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._pl_special_adjective(word, count) or word) return "{}{}{}".format(pre, plural, post) def compare(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return ( self._plequal(word1, word2, self.plural_noun) or self._plequal(word1, word2, self.plural_verb) or self._plequal(word1, word2, self.plural_adj) ) def compare_nouns(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_noun) def compare_verbs(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as verbs return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_verb) def compare_adjs(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_adj) def singular_noun(self, text, count=None, gender=None): """ Return the singular of text, where text is a plural noun. If count supplied, then return the singular if count is one of: 1, a, an, one, each, every, this, that or if count is None otherwise return text unchanged. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text sing = self._sinoun(word, count=count, gender=gender) if sing is not False: plural = self.postprocess( word, self._sinoun(word, count=count, gender=gender) ) return "{}{}{}".format(pre, plural, post) return False def _plequal(self, word1, word2, pl): classval = self.classical_dict.copy() self.classical_dict = all_classical.copy() if word1 == word2: return "eq" if word1 == pl(word2): return "p:s" if pl(word1) == word2: return "s:p" self.classical_dict = no_classical.copy() if word1 == pl(word2): return "p:s" if pl(word1) == word2: return "s:p" self.classical_dict = classval.copy() if pl == self.plural or pl == self.plural_noun: if self._pl_check_plurals_N(word1, word2): return "p:p" if self._pl_check_plurals_N(word2, word1): return "p:p" if pl == self.plural or pl == self.plural_adj: if self._pl_check_plurals_adj(word1, word2): return "p:p" return False def _pl_reg_plurals(self, pair, stems, end1, end2): pattern = r"({})({}\|\1{}|{}\|\1{})".format(stems, end1, end2, end2, end1) return bool(re.search(pattern, pair)) def _pl_check_plurals_N(self, word1, word2): stem_endings = ( (pl_sb_C_a_ata, "as", "ata"), (pl_sb_C_is_ides, "is", "ides"), (pl_sb_C_a_ae, "s", "e"), (pl_sb_C_en_ina, "ens", "ina"), (pl_sb_C_um_a, "ums", "a"), (pl_sb_C_us_i, "uses", "i"), (pl_sb_C_on_a, "ons", "a"), (pl_sb_C_o_i_stems, "os", "i"), (pl_sb_C_ex_ices, "exes", "ices"), (pl_sb_C_ix_ices, "ixes", "ices"), (pl_sb_C_i, "s", "i"), (pl_sb_C_im, "s", "im"), (".*eau", "s", "x"), (".*ieu", "s", "x"), (".*tri", "xes", "ces"), (".{2,}[yia]n", "xes", "ges"), ) pair = "{}|{}".format(word1, word2) return ( pair in pl_sb_irregular_s.values() or pair in pl_sb_irregular.values() or pair in pl_sb_irregular_caps.values() or any( self._pl_reg_plurals(pair, stems, end1, end2) for stems, end1, end2 in stem_endings ) ) def _pl_check_plurals_adj(self, word1, word2): word1a = word1[: word1.rfind("'")] if word1.endswith(("'s", "'")) else "" word2a = word2[: word2.rfind("'")] if word2.endswith(("'s", "'")) else "" return ( word1a and word2a and ( self._pl_check_plurals_N(word1a, word2a) or self._pl_check_plurals_N(word2a, word1a) ) ) def get_count(self, count=None): if count is None and self.persistent_count is not None: count = self.persistent_count if count is not None: count = ( 1 if ( (str(count) in pl_count_one) or ( self.classical_dict["zero"] and str(count).lower() in pl_count_zero ) ) else 2 ) else: count = "" return count # @profile def _plnoun(self, word, count=None): count = self.get_count(count) # DEFAULT TO PLURAL if count == 1: return word # HANDLE USER-DEFINED NOUNS value = self.ud_match(word, self.pl_sb_user_defined) if value is not None: return value # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS if word == "": return word lowerword = word.lower() if lowerword in pl_sb_uninflected_complete: return word if word in pl_sb_uninflected_caps: return word for k, v in pl_sb_uninflected_bysize.items(): if lowerword[-k:] in v: return word if self.classical_dict["herd"] and lowerword in pl_sb_uninflected_herd: return word # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) mo = re.search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, re.IGNORECASE) if mo and mo.group(2) != "": return "{}{}".format(self._plnoun(mo.group(1), 2), mo.group(2)) if " a " in lowerword or "-a-" in lowerword: mo = re.search(r"^(?:%s)$" % pl_sb_prep_dual_compound, word, re.IGNORECASE) if mo and mo.group(2) != "" and mo.group(3) != "": return "{}{}{}".format( self._plnoun(mo.group(1), 2), mo.group(2), self._plnoun(mo.group(3)) ) lowersplit = lowerword.split(" ") if len(lowersplit) >= 3: for numword in range(1, len(lowersplit) - 1): if lowersplit[numword] in pl_prep_list_da: return " ".join( lowersplit[: numword - 1] + [self._plnoun(lowersplit[numword - 1], 2)] + lowersplit[numword:] ) # only pluralize denominators in units mo = re.search( r"(?P.+)( (%s) .+)" % "|".join(["per", "a"]), lowerword ) if mo: index = len(mo.group("denominator")) return "{}{}".format(self._plnoun(word[:index]), word[index:]) # handle units given in degrees (only accept if # there is no more than one word following) # degree Celsius => degrees Celsius but degree # fahrenheit hour => degree fahrenheit hours if len(lowersplit) >= 2 and lowersplit[-2] in ["degree"]: return " ".join([self._plnoun(lowersplit[0])] + lowersplit[1:]) lowersplit = lowerword.split("-") if len(lowersplit) >= 3: for numword in range(1, len(lowersplit) - 1): if lowersplit[numword] in pl_prep_list_da: return " ".join( lowersplit[: numword - 1] + [ self._plnoun(lowersplit[numword - 1], 2) + "-" + lowersplit[numword] + "-" ] ) + " ".join(lowersplit[(numword + 1) :]) # HANDLE PRONOUNS for k, v in pl_pron_acc_keys_bysize.items(): if lowerword[-k:] in v: # ends with accusivate pronoun for pk, pv in pl_prep_bysize.items(): if lowerword[:pk] in pv: # starts with a prep if lowerword.split() == [lowerword[:pk], lowerword[-k:]]: # only whitespace in between return lowerword[:-k] + pl_pron_acc[lowerword[-k:]] try: return pl_pron_nom[word.lower()] except KeyError: pass try: return pl_pron_acc[word.lower()] except KeyError: pass # HANDLE ISOLATED IRREGULAR PLURALS wordsplit = word.split() wordlast = wordsplit[-1] lowerwordlast = wordlast.lower() if wordlast in list(pl_sb_irregular_caps.keys()): llen = len(wordlast) return "{}{}".format(word[:-llen], pl_sb_irregular_caps[wordlast]) if lowerwordlast in list(pl_sb_irregular.keys()): llen = len(lowerwordlast) return "{}{}".format(word[:-llen], pl_sb_irregular[lowerwordlast]) if (" ".join(wordsplit[-2:])).lower() in list(pl_sb_irregular_compound.keys()): llen = len( " ".join(wordsplit[-2:]) ) # TODO: what if 2 spaces between these words? return "{}{}".format( word[:-llen], pl_sb_irregular_compound[(" ".join(wordsplit[-2:])).lower()], ) if lowerword[-3:] == "quy": return word[:-1] + "ies" if lowerword[-6:] == "person": if self.classical_dict["persons"]: return word + "s" else: return word[:-4] + "ople" # HANDLE FAMILIES OF IRREGULAR PLURALS if lowerword[-3:] == "man": for k, v in pl_sb_U_man_mans_bysize.items(): if lowerword[-k:] in v: return word + "s" for k, v in pl_sb_U_man_mans_caps_bysize.items(): if word[-k:] in v: return word + "s" return word[:-3] + "men" if lowerword[-5:] == "mouse": return word[:-5] + "mice" if lowerword[-5:] == "louse": return word[:-5] + "lice" if lowerword[-5:] == "goose": return word[:-5] + "geese" if lowerword[-5:] == "tooth": return word[:-5] + "teeth" if lowerword[-4:] == "foot": return word[:-4] + "feet" if lowerword[-4:] == "taco": return word[:-5] + "tacos" if lowerword == "die": return "dice" # HANDLE UNASSIMILATED IMPORTS if lowerword[-4:] == "ceps": return word if lowerword[-4:] == "zoon": return word[:-2] + "a" if lowerword[-3:] in ("cis", "sis", "xis"): return word[:-2] + "es" for lastlet, d, numend, post in ( ("h", pl_sb_U_ch_chs_bysize, None, "s"), ("x", pl_sb_U_ex_ices_bysize, -2, "ices"), ("x", pl_sb_U_ix_ices_bysize, -2, "ices"), ("m", pl_sb_U_um_a_bysize, -2, "a"), ("s", pl_sb_U_us_i_bysize, -2, "i"), ("n", pl_sb_U_on_a_bysize, -2, "a"), ("a", pl_sb_U_a_ae_bysize, None, "e"), ): if lowerword[-1] == lastlet: # this test to add speed for k, v in d.items(): if lowerword[-k:] in v: return word[:numend] + post # HANDLE INCOMPLETELY ASSIMILATED IMPORTS if self.classical_dict["ancient"]: if lowerword[-4:] == "trix": return word[:-1] + "ces" if lowerword[-3:] in ("eau", "ieu"): return word + "x" if lowerword[-3:] in ("ynx", "inx", "anx") and len(word) > 4: return word[:-1] + "ges" for lastlet, d, numend, post in ( ("n", pl_sb_C_en_ina_bysize, -2, "ina"), ("x", pl_sb_C_ex_ices_bysize, -2, "ices"), ("x", pl_sb_C_ix_ices_bysize, -2, "ices"), ("m", pl_sb_C_um_a_bysize, -2, "a"), ("s", pl_sb_C_us_i_bysize, -2, "i"), ("s", pl_sb_C_us_us_bysize, None, ""), ("a", pl_sb_C_a_ae_bysize, None, "e"), ("a", pl_sb_C_a_ata_bysize, None, "ta"), ("s", pl_sb_C_is_ides_bysize, -1, "des"), ("o", pl_sb_C_o_i_bysize, -1, "i"), ("n", pl_sb_C_on_a_bysize, -2, "a"), ): if lowerword[-1] == lastlet: # this test to add speed for k, v in d.items(): if lowerword[-k:] in v: return word[:numend] + post for d, numend, post in ( (pl_sb_C_i_bysize, None, "i"), (pl_sb_C_im_bysize, None, "im"), ): for k, v in d.items(): if lowerword[-k:] in v: return word[:numend] + post # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS if lowerword in pl_sb_singular_s_complete: return word + "es" for k, v in pl_sb_singular_s_bysize.items(): if lowerword[-k:] in v: return word + "es" if lowerword[-2:] == "es" and word[0] == word[0].upper(): return word + "es" if lowerword[-1] == "z": for k, v in pl_sb_z_zes_bysize.items(): if lowerword[-k:] in v: return word + "es" if lowerword[-2:-1] != "z": return word + "zes" if lowerword[-2:] == "ze": for k, v in pl_sb_ze_zes_bysize.items(): if lowerword[-k:] in v: return word + "s" if lowerword[-2:] in ("ch", "sh", "zz", "ss") or lowerword[-1] == "x": return word + "es" # HANDLE ...f -> ...ves if lowerword[-3:] in ("elf", "alf", "olf"): return word[:-1] + "ves" if lowerword[-3:] == "eaf" and lowerword[-4:-3] != "d": return word[:-1] + "ves" if lowerword[-4:] in ("nife", "life", "wife"): return word[:-2] + "ves" if lowerword[-3:] == "arf": return word[:-1] + "ves" # HANDLE ...y if lowerword[-1] == "y": if lowerword[-2:-1] in "aeiou" or len(word) == 1: return word + "s" if self.classical_dict["names"]: if lowerword[-1] == "y" and word[0] == word[0].upper(): return word + "s" return word[:-1] + "ies" # HANDLE ...o if lowerword in pl_sb_U_o_os_complete: return word + "s" for k, v in pl_sb_U_o_os_bysize.items(): if lowerword[-k:] in v: return word + "s" if lowerword[-2:] in ("ao", "eo", "io", "oo", "uo"): return word + "s" if lowerword[-1] == "o": return word + "es" # OTHERWISE JUST ADD ...s return "%ss" % word def _pl_special_verb(self, word, count=None): if self.classical_dict["zero"] and str(count).lower() in pl_count_zero: return False count = self.get_count(count) if count == 1: return word # HANDLE USER-DEFINED VERBS value = self.ud_match(word, self.pl_v_user_defined) if value is not None: return value # HANDLE IRREGULAR PRESENT TENSE (SIMPLE AND COMPOUND) lowerword = word.lower() try: firstword = lowerword.split()[0] except IndexError: return False # word is '' if firstword in list(plverb_irregular_pres.keys()): return "{}{}".format( plverb_irregular_pres[firstword], word[len(firstword) :] ) # HANDLE IRREGULAR FUTURE, PRETERITE AND PERFECT TENSES if firstword in plverb_irregular_non_pres: return word # HANDLE PRESENT NEGATIONS (SIMPLE AND COMPOUND) if firstword.endswith("n't") and firstword[:-3] in list( plverb_irregular_pres.keys() ): return "{}n't{}".format( plverb_irregular_pres[firstword[:-3]], word[len(firstword) :] ) if firstword.endswith("n't"): return word # HANDLE SPECIAL CASES mo = re.search(r"^(%s)$" % plverb_special_s, word) if mo: return False if re.search(r"\s", word): return False if lowerword == "quizzes": return "quiz" # HANDLE STANDARD 3RD PERSON (CHOP THE ...(e)s OFF SINGLE WORDS) if ( lowerword[-4:] in ("ches", "shes", "zzes", "sses") or lowerword[-3:] == "xes" ): return word[:-2] if lowerword[-3:] == "ies" and len(word) > 3: return lowerword[:-3] + "y" if ( lowerword in pl_v_oes_oe or lowerword[-4:] in pl_v_oes_oe_endings_size4 or lowerword[-5:] in pl_v_oes_oe_endings_size5 ): return word[:-1] if lowerword.endswith("oes") and len(word) > 3: return lowerword[:-2] mo = re.search(r"^(.*[^s])s$", word, re.IGNORECASE) if mo: return mo.group(1) # OTHERWISE, A REGULAR VERB (HANDLE ELSEWHERE) return False def _pl_general_verb(self, word, count=None): count = self.get_count(count) if count == 1: return word # HANDLE AMBIGUOUS PRESENT TENSES (SIMPLE AND COMPOUND) mo = re.search( r"^(%s)((\s.*)?)$" % plverb_ambiguous_pres_keys, word, re.IGNORECASE ) if mo: return "{}{}".format( plverb_ambiguous_pres[mo.group(1).lower()], mo.group(2) ) # HANDLE AMBIGUOUS PRETERITE AND PERFECT TENSES mo = re.search( r"^(%s)((\s.*)?)$" % plverb_ambiguous_non_pres, word, re.IGNORECASE ) if mo: return word # OTHERWISE, 1st OR 2ND PERSON IS UNINFLECTED return word def _pl_special_adjective(self, word, count=None): count = self.get_count(count) if count == 1: return word # HANDLE USER-DEFINED ADJECTIVES value = self.ud_match(word, self.pl_adj_user_defined) if value is not None: return value # HANDLE KNOWN CASES mo = re.search(r"^(%s)$" % pl_adj_special_keys, word, re.IGNORECASE) if mo: return "%s" % (pl_adj_special[mo.group(1).lower()]) # HANDLE POSSESSIVES mo = re.search(r"^(%s)$" % pl_adj_poss_keys, word, re.IGNORECASE) if mo: return "%s" % (pl_adj_poss[mo.group(1).lower()]) mo = re.search(r"^(.*)'s?$", word) if mo: pl = self.plural_noun(mo.group(1)) trailing_s = "" if pl[-1] == "s" else "s" return "{}'{}".format(pl, trailing_s) # OTHERWISE, NO IDEA return False # @profile def _sinoun(self, word, count=None, gender=None): count = self.get_count(count) # DEFAULT TO PLURAL if count == 2: return word # SET THE GENDER try: if gender is None: gender = self.thegender elif gender not in singular_pronoun_genders: raise BadGenderError except (TypeError, IndexError): raise BadGenderError # HANDLE USER-DEFINED NOUNS value = self.ud_match(word, self.si_sb_user_defined) if value is not None: return value # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS if word == "": return word lowerword = word.lower() if word in si_sb_ois_oi_case: return word[:-1] if lowerword in pl_sb_uninflected_complete: return word if word in pl_sb_uninflected_caps: return word for k, v in pl_sb_uninflected_bysize.items(): if lowerword[-k:] in v: return word if self.classical_dict["herd"] and lowerword in pl_sb_uninflected_herd: return word if lowerword in pl_sb_C_us_us: return word # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) mo = re.search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, re.IGNORECASE) if mo and mo.group(2) != "": return "{}{}".format( self._sinoun(mo.group(1), 1, gender=gender), mo.group(2) ) lowersplit = lowerword.split(" ") if len(lowersplit) >= 3: for numword in range(1, len(lowersplit) - 1): if lowersplit[numword] in pl_prep_list_da: return " ".join( lowersplit[: numword - 1] + [ self._sinoun(lowersplit[numword - 1], 1, gender=gender) or lowersplit[numword - 1] ] + lowersplit[numword:] ) lowersplit = lowerword.split("-") if len(lowersplit) >= 3: for numword in range(1, len(lowersplit) - 1): if lowersplit[numword] in pl_prep_list_da: return " ".join( lowersplit[: numword - 1] + [ ( self._sinoun(lowersplit[numword - 1], 1, gender=gender) or lowersplit[numword - 1] ) + "-" + lowersplit[numword] + "-" ] ) + " ".join(lowersplit[(numword + 1) :]) # HANDLE PRONOUNS for k, v in si_pron_acc_keys_bysize.items(): if lowerword[-k:] in v: # ends with accusivate pronoun for pk, pv in pl_prep_bysize.items(): if lowerword[:pk] in pv: # starts with a prep if lowerword.split() == [lowerword[:pk], lowerword[-k:]]: # only whitespace in between return lowerword[:-k] + get_si_pron( "acc", lowerword[-k:], gender ) try: return get_si_pron("nom", word.lower(), gender) except KeyError: pass try: return get_si_pron("acc", word.lower(), gender) except KeyError: pass # HANDLE ISOLATED IRREGULAR PLURALS wordsplit = word.split() wordlast = wordsplit[-1] lowerwordlast = wordlast.lower() if wordlast in list(si_sb_irregular_caps.keys()): llen = len(wordlast) return "{}{}".format(word[:-llen], si_sb_irregular_caps[wordlast]) if lowerwordlast in list(si_sb_irregular.keys()): llen = len(lowerwordlast) return "{}{}".format(word[:-llen], si_sb_irregular[lowerwordlast]) if (" ".join(wordsplit[-2:])).lower() in list(si_sb_irregular_compound.keys()): llen = len( " ".join(wordsplit[-2:]) ) # TODO: what if 2 spaces between these words? return "{}{}".format( word[:-llen], si_sb_irregular_compound[(" ".join(wordsplit[-2:])).lower()], ) if lowerword[-5:] == "quies": return word[:-3] + "y" if lowerword[-7:] == "persons": return word[:-1] if lowerword[-6:] == "people": return word[:-4] + "rson" # HANDLE FAMILIES OF IRREGULAR PLURALS if lowerword[-4:] == "mans": for k, v in si_sb_U_man_mans_bysize.items(): if lowerword[-k:] in v: return word[:-1] for k, v in si_sb_U_man_mans_caps_bysize.items(): if word[-k:] in v: return word[:-1] if lowerword[-3:] == "men": return word[:-3] + "man" if lowerword[-4:] == "mice": return word[:-4] + "mouse" if lowerword[-4:] == "lice": return word[:-4] + "louse" if lowerword[-5:] == "geese": return word[:-5] + "goose" if lowerword[-5:] == "teeth": return word[:-5] + "tooth" if lowerword[-4:] == "feet": return word[:-4] + "foot" if lowerword == "dice": return "die" # HANDLE UNASSIMILATED IMPORTS if lowerword[-4:] == "ceps": return word if lowerword[-3:] == "zoa": return word[:-1] + "on" for lastlet, d, numend, post in ( ("s", si_sb_U_ch_chs_bysize, -1, ""), ("s", si_sb_U_ex_ices_bysize, -4, "ex"), ("s", si_sb_U_ix_ices_bysize, -4, "ix"), ("a", si_sb_U_um_a_bysize, -1, "um"), ("i", si_sb_U_us_i_bysize, -1, "us"), ("a", si_sb_U_on_a_bysize, -1, "on"), ("e", si_sb_U_a_ae_bysize, -1, ""), ): if lowerword[-1] == lastlet: # this test to add speed for k, v in d.items(): if lowerword[-k:] in v: return word[:numend] + post # HANDLE INCOMPLETELY ASSIMILATED IMPORTS if self.classical_dict["ancient"]: if lowerword[-6:] == "trices": return word[:-3] + "x" if lowerword[-4:] in ("eaux", "ieux"): return word[:-1] if lowerword[-5:] in ("ynges", "inges", "anges") and len(word) > 6: return word[:-3] + "x" for lastlet, d, numend, post in ( ("a", si_sb_C_en_ina_bysize, -3, "en"), ("s", si_sb_C_ex_ices_bysize, -4, "ex"), ("s", si_sb_C_ix_ices_bysize, -4, "ix"), ("a", si_sb_C_um_a_bysize, -1, "um"), ("i", si_sb_C_us_i_bysize, -1, "us"), ("s", pl_sb_C_us_us_bysize, None, ""), ("e", si_sb_C_a_ae_bysize, -1, ""), ("a", si_sb_C_a_ata_bysize, -2, ""), ("s", si_sb_C_is_ides_bysize, -3, "s"), ("i", si_sb_C_o_i_bysize, -1, "o"), ("a", si_sb_C_on_a_bysize, -1, "on"), ("m", si_sb_C_im_bysize, -2, ""), ("i", si_sb_C_i_bysize, -1, ""), ): if lowerword[-1] == lastlet: # this test to add speed for k, v in d.items(): if lowerword[-k:] in v: return word[:numend] + post # HANDLE PLURLS ENDING IN uses -> use if ( lowerword[-6:] == "houses" or word in si_sb_uses_use_case or lowerword in si_sb_uses_use ): return word[:-1] # HANDLE PLURLS ENDING IN ies -> ie if word in si_sb_ies_ie_case or lowerword in si_sb_ies_ie: return word[:-1] # HANDLE PLURLS ENDING IN oes -> oe if ( lowerword[-5:] == "shoes" or word in si_sb_oes_oe_case or lowerword in si_sb_oes_oe ): return word[:-1] # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS if word in si_sb_sses_sse_case or lowerword in si_sb_sses_sse: return word[:-1] if lowerword in si_sb_singular_s_complete: return word[:-2] for k, v in si_sb_singular_s_bysize.items(): if lowerword[-k:] in v: return word[:-2] if lowerword[-4:] == "eses" and word[0] == word[0].upper(): return word[:-2] if lowerword in si_sb_z_zes: return word[:-2] if lowerword in si_sb_zzes_zz: return word[:-2] if lowerword[-4:] == "zzes": return word[:-3] if word in si_sb_ches_che_case or lowerword in si_sb_ches_che: return word[:-1] if lowerword[-4:] in ("ches", "shes"): return word[:-2] if lowerword in si_sb_xes_xe: return word[:-1] if lowerword[-3:] == "xes": return word[:-2] # HANDLE ...f -> ...ves if word in si_sb_ves_ve_case or lowerword in si_sb_ves_ve: return word[:-1] if lowerword[-3:] == "ves": if lowerword[-5:-3] in ("el", "al", "ol"): return word[:-3] + "f" if lowerword[-5:-3] == "ea" and word[-6:-5] != "d": return word[:-3] + "f" if lowerword[-5:-3] in ("ni", "li", "wi"): return word[:-3] + "fe" if lowerword[-5:-3] == "ar": return word[:-3] + "f" # HANDLE ...y if lowerword[-2:] == "ys": if len(lowerword) > 2 and lowerword[-3] in "aeiou": return word[:-1] if self.classical_dict["names"]: if lowerword[-2:] == "ys" and word[0] == word[0].upper(): return word[:-1] if lowerword[-3:] == "ies": return word[:-3] + "y" # HANDLE ...o if lowerword[-2:] == "os": if lowerword in si_sb_U_o_os_complete: return word[:-1] for k, v in si_sb_U_o_os_bysize.items(): if lowerword[-k:] in v: return word[:-1] if lowerword[-3:] in ("aos", "eos", "ios", "oos", "uos"): return word[:-1] if lowerword[-3:] == "oes": return word[:-2] # UNASSIMILATED IMPORTS FINAL RULE if word in si_sb_es_is: return word[:-2] + "is" # OTHERWISE JUST REMOVE ...s if lowerword[-1] == "s": return word[:-1] # COULD NOT FIND SINGULAR return False # ADJECTIVES def a(self, text, count=1): """ Return the appropriate indefinite article followed by text. The indefinite article is either 'a' or 'an'. If count is not one, then return count followed by text instead of 'a' or 'an'. Whitespace at the start and end is preserved. """ mo = re.search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", text, re.IGNORECASE) if mo: word = mo.group(2) if not word: return text pre = mo.group(1) post = mo.group(3) result = self._indef_article(word, count) return "{}{}{}".format(pre, result, post) return "" an = a def _indef_article(self, word, count): mycount = self.get_count(count) if mycount != 1: return "{} {}".format(count, word) # HANDLE USER-DEFINED VARIANTS value = self.ud_match(word, self.A_a_user_defined) if value is not None: return "{} {}".format(value, word) # HANDLE ORDINAL FORMS for a in ((r"^(%s)" % A_ordinal_a, "a"), (r"^(%s)" % A_ordinal_an, "an")): mo = re.search(a[0], word, re.IGNORECASE) if mo: return "{} {}".format(a[1], word) # HANDLE SPECIAL CASES for a in ( (r"^(%s)" % A_explicit_an, "an"), (r"^[aefhilmnorsx]$", "an"), (r"^[bcdgjkpqtuvwyz]$", "a"), ): mo = re.search(a[0], word, re.IGNORECASE) if mo: return "{} {}".format(a[1], word) # HANDLE ABBREVIATIONS for a in ( (r"(%s)" % A_abbrev, "an", re.VERBOSE), (r"^[aefhilmnorsx][.-]", "an", re.IGNORECASE), (r"^[a-z][.-]", "a", re.IGNORECASE), ): mo = re.search(a[0], word, a[2]) if mo: return "{} {}".format(a[1], word) # HANDLE CONSONANTS mo = re.search(r"^[^aeiouy]", word, re.IGNORECASE) if mo: return "a %s" % word # HANDLE SPECIAL VOWEL-FORMS for a in ( (r"^e[uw]", "a"), (r"^onc?e\b", "a"), (r"^onetime\b", "a"), (r"^uni([^nmd]|mo)", "a"), (r"^u[bcfghjkqrst][aeiou]", "a"), (r"^ukr", "a"), (r"^(%s)" % A_explicit_a, "a"), ): mo = re.search(a[0], word, re.IGNORECASE) if mo: return "{} {}".format(a[1], word) # HANDLE SPECIAL CAPITALS mo = re.search(r"^U[NK][AIEO]?", word) if mo: return "a %s" % word # HANDLE VOWELS mo = re.search(r"^[aeiou]", word, re.IGNORECASE) if mo: return "an %s" % word # HANDLE y... (BEFORE CERTAIN CONSONANTS IMPLIES (UNNATURALIZED) "i.." SOUND) mo = re.search(r"^(%s)" % A_y_cons, word, re.IGNORECASE) if mo: return "an %s" % word # OTHERWISE, GUESS "a" return "a %s" % word # 2. TRANSLATE ZERO-QUANTIFIED $word TO "no plural($word)" def no(self, text, count=None): """ If count is 0, no, zero or nil, return 'no' followed by the plural of text. If count is one of: 1, a, an, one, each, every, this, that return count followed by text. Otherwise return count follow by the plural of text. In the return value count is always followed by a space. Whitespace at the start and end is preserved. """ if count is None and self.persistent_count is not None: count = self.persistent_count if count is None: count = 0 mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text) pre = mo.group(1) word = mo.group(2) post = mo.group(3) if str(count).lower() in pl_count_zero: return "{}no {}{}".format(pre, self.plural(word, 0), post) else: return "{}{} {}{}".format(pre, count, self.plural(word, count), post) # PARTICIPLES def present_participle(self, word): """ Return the present participle for word. word is the 3rd person singular verb. """ plv = self.plural_verb(word, 2) for pat, repl in ( (r"ie$", r"y"), (r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule? (r"([auy])e$", r"\g<1>"), (r"ski$", r"ski"), (r"[^b]i$", r""), (r"^(are|were)$", r"be"), (r"^(had)$", r"hav"), (r"^(hoe)$", r"\g<1>"), (r"([^e])e$", r"\g<1>"), (r"er$", r"er"), (r"([^aeiou][aeiouy]([bdgmnprst]))$", r"\g<1>\g<2>"), ): (ans, num) = re.subn(pat, repl, plv) if num: return "%sing" % ans return "%sing" % ans # NUMERICAL INFLECTIONS def ordinal(self, num): """ Return the ordinal of num. num can be an integer or text e.g. ordinal(1) returns '1st' ordinal('one') returns 'first' """ if re.match(r"\d", str(num)): try: num % 2 n = num except TypeError: if "." in str(num): try: # numbers after decimal, # so only need last one for ordinal n = int(num[-1]) except ValueError: # ends with '.', so need to use whole string n = int(num[:-1]) else: n = int(num) try: post = nth[n % 100] except KeyError: post = nth[n % 10] return "{}{}".format(num, post) else: mo = re.search(r"(%s)\Z" % ordinal_suff, num) try: post = ordinal[mo.group(1)] return re.sub(r"(%s)\Z" % ordinal_suff, post, num) except AttributeError: return "%sth" % num def millfn(self, ind=0): if ind > len(mill) - 1: print3("number out of range") raise NumOutOfRangeError return mill[ind] def unitfn(self, units, mindex=0): return "{}{}".format(unit[units], self.millfn(mindex)) def tenfn(self, tens, units, mindex=0): if tens != 1: return "{}{}{}{}".format( ten[tens], "-" if tens and units else "", unit[units], self.millfn(mindex), ) return "{}{}".format(teen[units], mill[mindex]) def hundfn(self, hundreds, tens, units, mindex): if hundreds: andword = " %s " % self.number_args["andword"] if tens or units else "" return "{} hundred{}{}{}, ".format( unit[hundreds], # use unit not unitfn as simpler andword, self.tenfn(tens, units), self.millfn(mindex), ) if tens or units: return "{}{}, ".format(self.tenfn(tens, units), self.millfn(mindex)) return "" def group1sub(self, mo): units = int(mo.group(1)) if units == 1: return " %s, " % self.number_args["one"] elif units: return "%s, " % unit[units] else: return " %s, " % self.number_args["zero"] def group1bsub(self, mo): units = int(mo.group(1)) if units: return "%s, " % unit[units] else: return " %s, " % self.number_args["zero"] def group2sub(self, mo): tens = int(mo.group(1)) units = int(mo.group(2)) if tens: return "%s, " % self.tenfn(tens, units) if units: return " {} {}, ".format(self.number_args["zero"], unit[units]) return " {} {}, ".format(self.number_args["zero"], self.number_args["zero"]) def group3sub(self, mo): hundreds = int(mo.group(1)) tens = int(mo.group(2)) units = int(mo.group(3)) if hundreds == 1: hunword = " %s" % self.number_args["one"] elif hundreds: hunword = "%s" % unit[hundreds] else: hunword = " %s" % self.number_args["zero"] if tens: tenword = self.tenfn(tens, units) elif units: tenword = " {} {}".format(self.number_args["zero"], unit[units]) else: tenword = " {} {}".format( self.number_args["zero"], self.number_args["zero"] ) return "{} {}, ".format(hunword, tenword) def hundsub(self, mo): ret = self.hundfn( int(mo.group(1)), int(mo.group(2)), int(mo.group(3)), self.mill_count ) self.mill_count += 1 return ret def tensub(self, mo): return "%s, " % self.tenfn(int(mo.group(1)), int(mo.group(2)), self.mill_count) def unitsub(self, mo): return "%s, " % self.unitfn(int(mo.group(1)), self.mill_count) def enword(self, num, group): # import pdb # pdb.set_trace() if group == 1: num = re.sub(r"(\d)", self.group1sub, num) elif group == 2: num = re.sub(r"(\d)(\d)", self.group2sub, num) num = re.sub(r"(\d)", self.group1bsub, num, 1) elif group == 3: num = re.sub(r"(\d)(\d)(\d)", self.group3sub, num) num = re.sub(r"(\d)(\d)", self.group2sub, num, 1) num = re.sub(r"(\d)", self.group1sub, num, 1) elif int(num) == 0: num = self.number_args["zero"] elif int(num) == 1: num = self.number_args["one"] else: num = num.lstrip().lstrip("0") self.mill_count = 0 # surely there's a better way to do the next bit mo = re.search(r"(\d)(\d)(\d)(?=\D*\Z)", num) while mo: num = re.sub(r"(\d)(\d)(\d)(?=\D*\Z)", self.hundsub, num, 1) mo = re.search(r"(\d)(\d)(\d)(?=\D*\Z)", num) num = re.sub(r"(\d)(\d)(?=\D*\Z)", self.tensub, num, 1) num = re.sub(r"(\d)(?=\D*\Z)", self.unitsub, num, 1) return num def blankfn(self, mo): """ do a global blank replace TODO: surely this can be done with an option to re.sub rather than this fn """ return "" def commafn(self, mo): """ do a global ',' replace TODO: surely this can be done with an option to re.sub rather than this fn """ return "," def spacefn(self, mo): """ do a global ' ' replace TODO: surely this can be done with an option to re.sub rather than this fn """ return " " def number_to_words( self, num, wantlist=False, group=0, comma=",", andword="and", zero="zero", one="one", decimal="point", threshold=None, ): """ Return a number in words. group = 1, 2 or 3 to group numbers before turning into words comma: define comma andword: word for 'and'. Can be set to ''. e.g. "one hundred and one" vs "one hundred one" zero: word for '0' one: word for '1' decimal: word for decimal point threshold: numbers above threshold not turned into words parameters not remembered from last call. Departure from Perl version. """ self.number_args = dict(andword=andword, zero=zero, one=one) num = "%s" % num # Handle "stylistic" conversions (up to a given threshold)... if threshold is not None and float(num) > threshold: spnum = num.split(".", 1) while comma: (spnum[0], n) = re.subn(r"(\d)(\d{3}(?:,|\Z))", r"\1,\2", spnum[0]) if n == 0: break try: return "{}.{}".format(spnum[0], spnum[1]) except IndexError: return "%s" % spnum[0] if group < 0 or group > 3: raise BadChunkingOptionError nowhite = num.lstrip() if nowhite[0] == "+": sign = "plus" elif nowhite[0] == "-": sign = "minus" else: sign = "" myord = num[-2:] in ("st", "nd", "rd", "th") if myord: num = num[:-2] finalpoint = False if decimal: if group != 0: chunks = num.split(".") else: chunks = num.split(".", 1) if chunks[-1] == "": # remove blank string if nothing after decimal chunks = chunks[:-1] finalpoint = True # add 'point' to end of output else: chunks = [num] first = 1 loopstart = 0 if chunks[0] == "": first = 0 if len(chunks) > 1: loopstart = 1 for i in range(loopstart, len(chunks)): chunk = chunks[i] # remove all non numeric \D chunk = re.sub(r"\D", self.blankfn, chunk) if chunk == "": chunk = "0" if group == 0 and (first == 0 or first == ""): chunk = self.enword(chunk, 1) else: chunk = self.enword(chunk, group) if chunk[-2:] == ", ": chunk = chunk[:-2] chunk = re.sub(r"\s+,", self.commafn, chunk) if group == 0 and first: chunk = re.sub(r", (\S+)\s+\Z", " %s \\1" % andword, chunk) chunk = re.sub(r"\s+", self.spacefn, chunk) # chunk = re.sub(r"(\A\s|\s\Z)", self.blankfn, chunk) chunk = chunk.strip() if first: first = "" chunks[i] = chunk numchunks = [] if first != 0: numchunks = chunks[0].split("%s " % comma) if myord and numchunks: # TODO: can this be just one re as it is in perl? mo = re.search(r"(%s)\Z" % ordinal_suff, numchunks[-1]) if mo: numchunks[-1] = re.sub( r"(%s)\Z" % ordinal_suff, ordinal[mo.group(1)], numchunks[-1] ) else: numchunks[-1] += "th" for chunk in chunks[1:]: numchunks.append(decimal) numchunks.extend(chunk.split("%s " % comma)) if finalpoint: numchunks.append(decimal) # wantlist: Perl list context. can explictly specify in Python if wantlist: if sign: numchunks = [sign] + numchunks return numchunks elif group: signout = "%s " % sign if sign else "" return "{}{}".format(signout, ", ".join(numchunks)) else: signout = "%s " % sign if sign else "" num = "{}{}".format(signout, numchunks.pop(0)) if decimal is None: first = True else: first = not num.endswith(decimal) for nc in numchunks: if nc == decimal: num += " %s" % nc first = 0 elif first: num += "{} {}".format(comma, nc) else: num += " %s" % nc return num # Join words with commas and a trailing 'and' (when appropriate)... def join( self, words, sep=None, sep_spaced=True, final_sep=None, conj="and", conj_spaced=True, ): """ Join words into a list. e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly' options: conj: replacement for 'and' sep: separator. default ',', unless ',' is in the list then ';' final_sep: final separator. default ',', unless ',' is in the list then ';' conj_spaced: boolean. Should conj have spaces around it """ if not words: return "" if len(words) == 1: return words[0] if conj_spaced: if conj == "": conj = " " else: conj = " %s " % conj if len(words) == 2: return "{}{}{}".format(words[0], conj, words[1]) if sep is None: if "," in "".join(words): sep = ";" else: sep = "," if final_sep is None: final_sep = sep final_sep = "{}{}".format(final_sep, conj) if sep_spaced: sep += " " return "{}{}{}".format(sep.join(words[0:-1]), final_sep, words[-1]) inflect-2.1.0/pyproject.toml0000644000076500000240000000012013371552615016435 0ustar jaracostaff00000000000000[build-system] requires = ["setuptools>=30.3", "wheel", "setuptools_scm>=1.15"] inflect-2.1.0/setup.cfg0000644000076500000240000000022113372337712015344 0ustar jaracostaff00000000000000[bdist_wheel] universal = 1 [flake8] max-line-length = 99 [metadata] long_description = file:README.rst [egg_info] tag_build = tag_date = 0 inflect-2.1.0/setup.py0000644000076500000240000000254613372337710015247 0ustar jaracostaff00000000000000import inflect import setuptools setuptools.setup( name="inflect", version=inflect.__version__, description="Correctly generate plurals, singular nouns, ordinals, " "indefinite articles; convert numbers to words", author="Paul Dyson", author_email="pwdyson@yahoo.com", maintainer="Alex Gronholm", maintainer_email="alex.gronholm@nextday.fi", url="https://github.com/jazzband/inflect", py_modules=["inflect"], provides=["inflect"], keywords=["plural", "inflect", "participle"], classifiers=[ "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", setup_requires=["setuptools_scm"], ) inflect-2.1.0/tests/0000755000076500000240000000000013372337712014672 5ustar jaracostaff00000000000000inflect-2.1.0/tests/__init__.py0000644000076500000240000000000013370072435016765 0ustar jaracostaff00000000000000inflect-2.1.0/tests/inflections.txt0000644000076500000240000010515013372337701017750 0ustar jaracostaff00000000000000 a -> as # NOUN FORM TODO:sing a -> some # INDEFINITE ARTICLE TODO: A.C.R.O.N.Y.M. -> A.C.R.O.N.Y.M.s abscissa -> abscissas|abscissae Achinese -> Achinese acropolis -> acropolises adieu -> adieus|adieux adjutant general -> adjutant generals aegis -> aegises afflatus -> afflatuses afreet -> afreets|afreeti afrit -> afrits|afriti agendum -> agenda aide-de-camp -> aides-de-camp Alabaman -> Alabamans albino -> albinos album -> albums Alfurese -> Alfurese alga -> algae alias -> aliases alto -> altos|alti alumna -> alumnae alumnus -> alumni alveolus -> alveoli TODO:siverb am -> are TODO:siverb am going -> are going ambassador-at-large -> ambassadors-at-large Amboinese -> Amboinese Americanese -> Americanese amoeba -> amoebas|amoebae Amoyese -> Amoyese TODO:siadj an -> some # INDEFINITE ARTICLE analysis -> analyses anathema -> anathemas|anathemata Andamanese -> Andamanese Angolese -> Angolese Annamese -> Annamese antenna -> antennas|antennae anus -> anuses apex -> apexes|apices TODO:siadj apex's -> apexes'|apices' # POSSESSIVE FORM aphelion -> aphelia apparatus -> apparatuses|apparatus appendix -> appendixes|appendices apple -> apples aquarium -> aquariums|aquaria Aragonese -> Aragonese Arakanese -> Arakanese archipelago -> archipelagos TODO:siverb are -> are TODO:siverb are made -> are made armadillo -> armadillos arpeggio -> arpeggios arthritis -> arthritises|arthritides asbestos -> asbestoses asparagus -> asparaguses ass -> asses Assamese -> Assamese asylum -> asylums asyndeton -> asyndeta at it -> at them # ACCUSATIVE ataman -> atamans TODO:siverb ate -> ate atlas -> atlases|atlantes atman -> atmas TODO:singular_noun attorney general -> attorneys general attorney of record -> attorneys of record aurora -> auroras|aurorae auto -> autos auto-da-fe -> autos-da-fe aviatrix -> aviatrixes|aviatrices TODO:siadj aviatrix's -> aviatrixes'|aviatrices' Avignonese -> Avignonese axe -> axes TODO:singular_noun 2 anwers! axis -> axes axman -> axmen Azerbaijanese -> Azerbaijanese bacillus -> bacilli bacterium -> bacteria Bahaman -> Bahamans Balinese -> Balinese bamboo -> bamboos banjo -> banjoes bass -> basses # INSTRUMENT, NOT FISH basso -> bassos|bassi bathos -> bathoses beau -> beaus|beaux beef -> beefs|beeves beneath it -> beneath them # ACCUSATIVE Bengalese -> Bengalese bent -> bent # VERB FORM bent -> bents # NOUN FORM Bernese -> Bernese Bhutanese -> Bhutanese bias -> biases biceps -> biceps bison -> bisons|bison blouse -> blouses Bolognese -> Bolognese bonus -> bonuses Borghese -> Borghese boss -> bosses Bostonese -> Bostonese box -> boxes boy -> boys bravo -> bravoes bream -> bream breeches -> breeches bride-to-be -> brides-to-be Brigadier General -> Brigadier Generals britches -> britches bronchitis -> bronchitises|bronchitides bronchus -> bronchi brother -> brothers|brethren TODO: brother's -> brothers'|brethren's buffalo -> buffaloes|buffalo Buginese -> Buginese buoy -> buoys bureau -> bureaus|bureaux Burman -> Burmans Burmese -> Burmese bursitis -> bursitises|bursitides bus -> buses buzz -> buzzes buzzes -> buzz # VERB FORM by it -> by them # ACCUSATIVE caddis -> caddises caiman -> caimans cake -> cakes Calabrese -> Calabrese calf -> calves callus -> calluses Camaldolese -> Camaldolese cameo -> cameos campus -> campuses can -> cans # NOUN FORM can -> can # VERB FORM (all pers.) can't -> can't # VERB FORM candelabrum -> candelabra cannabis -> cannabises TODO:siverb canoes -> canoe canto -> cantos Cantonese -> Cantonese cantus -> cantus canvas -> canvases CAPITAL -> CAPITALS carcinoma -> carcinomas|carcinomata care -> cares cargo -> cargoes caribou -> caribous|caribou Carlylese -> Carlylese carmen -> carmina carp -> carp Cassinese -> Cassinese cat -> cats catfish -> catfish cayman -> caymans Celanese -> Celanese ceriman -> cerimans cervid -> cervids Ceylonese -> Ceylonese chairman -> chairmen chamois -> chamois chaos -> chaoses chapeau -> chapeaus|chapeaux charisma -> charismas|charismata TODO:siverb chases -> chase chassis -> chassis chateau -> chateaus|chateaux cherub -> cherubs|cherubim chickenpox -> chickenpox chief -> chiefs child -> children Chinese -> Chinese chorus -> choruses chrysalis -> chrysalises|chrysalides church -> churches cicatrix -> cicatrixes|cicatrices circus -> circuses class -> classes classes -> class # VERB FORM clippers -> clippers clitoris -> clitorises|clitorides cod -> cod codex -> codices coitus -> coitus commando -> commandos compendium -> compendiums|compendia coney -> coneys Congoese -> Congoese Congolese -> Congolese conspectus -> conspectuses contralto -> contraltos|contralti contretemps -> contretemps conundrum -> conundrums corps -> corps corpus -> corpuses|corpora cortex -> cortexes|cortices cosmos -> cosmoses TODO:singular_noun court martial -> courts martial cow -> cows|kine cranium -> craniums|crania crescendo -> crescendos criterion -> criteria curriculum -> curriculums|curricula czech -> czechs dais -> daises data point -> data points datum -> data debris -> debris decorum -> decorums deer -> deer delphinium -> delphiniums desideratum -> desiderata desman -> desmans diabetes -> diabetes dictum -> dictums|dicta TODO:siverb did -> did TODO:siverb did need -> did need digitalis -> digitalises dingo -> dingoes diploma -> diplomas|diplomata discus -> discuses dish -> dishes ditto -> dittos djinn -> djinn TODO:siverb does -> do TODO:siverb doesn't -> don't # VERB FORM dog -> dogs dogma -> dogmas|dogmata dolman -> dolmans dominatrix -> dominatrixes|dominatrices domino -> dominoes Dongolese -> Dongolese dormouse -> dormice drama -> dramas|dramata drum -> drums dwarf -> dwarves dynamo -> dynamos edema -> edemas|edemata eland -> elands|eland elf -> elves elk -> elks|elk embryo -> embryos emporium -> emporiums|emporia encephalitis -> encephalitises|encephalitides enconium -> enconiums|enconia enema -> enemas|enemata enigma -> enigmas|enigmata epidermis -> epidermises epididymis -> epididymises|epididymides erratum -> errata ethos -> ethoses eucalyptus -> eucalyptuses eunuch -> eunuchs extremum -> extrema eyas -> eyases factotum -> factotums farman -> farmans Faroese -> Faroese fauna -> faunas|faunae fax -> faxes Ferrarese -> Ferrarese ferry -> ferries fetus -> fetuses fiance -> fiances fiancee -> fiancees fiasco -> fiascos fish -> fish fizz -> fizzes flamingo -> flamingoes flittermouse -> flittermice TODO:siverb floes -> floe flora -> floras|florae flounder -> flounder focus -> focuses|foci foetus -> foetuses folio -> folios Foochowese -> Foochowese foot -> feet TODO:siadj foot's -> feet's # POSSESSIVE FORM foramen -> foramens|foramina TODO:siverb foreshoes -> foreshoe formula -> formulas|formulae forum -> forums TODO:siverb fought -> fought fox -> foxes TODO:singular_noun 2 different returns from him -> from them from it -> from them # ACCUSATIVE fungus -> funguses|fungi Gabunese -> Gabunese gallows -> gallows ganglion -> ganglions|ganglia gas -> gases gateau -> gateaus|gateaux TODO:siverb gave -> gave general -> generals generalissimo -> generalissimos Genevese -> Genevese genie -> genies|genii TODO:singular_noun 2 diff return values! genius -> geniuses|genii Genoese -> Genoese genus -> genera German -> Germans ghetto -> ghettos Gilbertese -> Gilbertese glottis -> glottises Goanese -> Goanese goat -> goats goose -> geese TODO:singular_noun Governor General -> Governors General goy -> goys|goyim graffiti -> graffiti TODO:singular_noun 2 diff ret values graffito -> graffiti grizzly -> grizzlies guano -> guanos guardsman -> guardsmen Guianese -> Guianese gumma -> gummas|gummata TODO:siverb gumshoes -> gumshoe gunman -> gunmen gymnasium -> gymnasiums|gymnasia TODO:siverb had -> had TODO:siverb had thought -> had thought Hainanese -> Hainanese TODO:siverb hammertoes -> hammertoe handkerchief -> handkerchiefs Hararese -> Hararese Harlemese -> Harlemese harman -> harmans harmonium -> harmoniums TODO:siverb has -> have TODO:siverb has become -> have become TODO:siverb has been -> have been TODO:siverb has-been -> has-beens hasn't -> haven't # VERB FORM Havanese -> Havanese TODO:siverb have -> have TODO:siverb have conceded -> have conceded TODO:singular_noun 2 values he -> they headquarters -> headquarters Heavenese -> Heavenese helix -> helices hepatitis -> hepatitises|hepatitides TODO:singular_noun 2 values her -> them # PRONOUN TODO:singular_noun 2 values her -> their # POSSESSIVE ADJ hero -> heroes herpes -> herpes TODO:singular_noun 2 values hers -> theirs # POSSESSIVE NOUN TODO:singular_noun 2 values herself -> themselves hetman -> hetmans hiatus -> hiatuses|hiatus highlight -> highlights hijinks -> hijinks TODO:singular_noun 2 values him -> them TODO:singular_noun 2 values himself -> themselves hippopotamus -> hippopotamuses|hippopotami Hiroshiman -> Hiroshimans TODO:singular_noun 2 values his -> their # POSSESSIVE ADJ TODO:singular_noun 2 values his -> theirs # POSSESSIVE NOUN TODO:siverb hoes -> hoe honorarium -> honorariums|honoraria hoof -> hoofs|hooves Hoosierese -> Hoosierese TODO:siverb horseshoes -> horseshoe Hottentotese -> Hottentotese house -> houses housewife -> housewives hubris -> hubrises human -> humans Hunanese -> Hunanese hydra -> hydras|hydrae hyperbaton -> hyperbata hyperbola -> hyperbolas|hyperbolae I -> we ibis -> ibises ignoramus -> ignoramuses impetus -> impetuses|impetus incubus -> incubuses|incubi index -> indexes|indices Indochinese -> Indochinese inferno -> infernos innings -> innings TODO:singular_noun Inspector General -> Inspectors General interregnum -> interregnums|interregna iris -> irises|irides TODO:siverb is -> are TODO:siverb is eaten -> are eaten isn't -> aren't # VERB FORM it -> they # NOMINATIVE TODO:siadj its -> their # POSSESSIVE FORM itself -> themselves jackanapes -> jackanapes Japanese -> Japanese Javanese -> Javanese Jerry -> Jerrys jerry -> jerries jinx -> jinxes jinxes -> jinx # VERB FORM Johnsonese -> Johnsonese Jones -> Joneses jumbo -> jumbos Kanarese -> Kanarese Kiplingese -> Kiplingese knife -> knives # NOUN FORM knife -> knife # VERB FORM (1st/2nd pers.) knifes -> knife # VERB FORM (3rd pers.) Kongoese -> Kongoese Kongolese -> Kongolese lacuna -> lacunas|lacunae lady in waiting -> ladies in waiting Lapponese -> Lapponese larynx -> larynxes|larynges latex -> latexes|latices lawman -> lawmen layman -> laymen leaf -> leaves # NOUN FORM leaf -> leaf # VERB FORM (1st/2nd pers.) leafs -> leaf # VERB FORM (3rd pers.) Lebanese -> Lebanese leman -> lemans lemma -> lemmas|lemmata lens -> lenses Leonese -> Leonese lick of the cat -> licks of the cat Lieutenant General -> Lieutenant Generals life -> lives Liman -> Limans lingo -> lingos loaf -> loaves locus -> loci Londonese -> Londonese Lorrainese -> Lorrainese lothario -> lotharios louse -> lice Lucchese -> Lucchese lumbago -> lumbagos lumen -> lumens|lumina lummox -> lummoxes lustrum -> lustrums|lustra lyceum -> lyceums lymphoma -> lymphomas|lymphomata lynx -> lynxes Lyonese -> Lyonese TODO: M.I.A. -> M.I.A.s Macanese -> Macanese Macassarese -> Macassarese mackerel -> mackerel macro -> macros TODO:siverb made -> made madman -> madmen Madurese -> Madurese magma -> magmas|magmata magneto -> magnetos Major General -> Major Generals Malabarese -> Malabarese Maltese -> Maltese man -> men mandamus -> mandamuses manifesto -> manifestos mantis -> mantises marquis -> marquises Mary -> Marys maximum -> maximums|maxima measles -> measles medico -> medicos medium -> mediums|media TODO:siadj medium's -> mediums'|media's medusa -> medusas|medusae memorandum -> memorandums|memoranda meniscus -> menisci merman -> mermen Messinese -> Messinese metamorphosis -> metamorphoses metropolis -> metropolises mews -> mews miasma -> miasmas|miasmata Milanese -> Milanese milieu -> milieus|milieux millennium -> millenniums|millennia minimum -> minimums|minima minx -> minxes miss -> miss # VERB FORM (1st/2nd pers.) miss -> misses # NOUN FORM misses -> miss # VERB FORM (3rd pers.) TODO:siverb mistletoes -> mistletoe mittamus -> mittamuses Modenese -> Modenese momentum -> momentums|momenta money -> monies mongoose -> mongooses moose -> moose mother-in-law -> mothers-in-law mouse -> mice mumps -> mumps Muranese -> Muranese murex -> murices museum -> museums mustachio -> mustachios TODO:siadj my -> our # POSSESSIVE FORM myself -> ourselves mythos -> mythoi Nakayaman -> Nakayamans Nankingese -> Nankingese nasturtium -> nasturtiums Navarrese -> Navarrese nebula -> nebulas|nebulae Nepalese -> Nepalese neuritis -> neuritises|neuritides neurosis -> neuroses news -> news nexus -> nexus Niasese -> Niasese Nicobarese -> Nicobarese nimbus -> nimbuses|nimbi Nipponese -> Nipponese no -> noes Norman -> Normans nostrum -> nostrums noumenon -> noumena nova -> novas|novae nucleolus -> nucleoluses|nucleoli nucleus -> nuclei numen -> numina oaf -> oafs TODO:siverb oboes -> oboe occiput -> occiputs|occipita octavo -> octavos octopus -> octopuses|octopodes oedema -> oedemas|oedemata Oklahoman -> Oklahomans omnibus -> omnibuses on it -> on them # ACCUSATIVE onus -> onuses opera -> operas optimum -> optimums|optima opus -> opuses|opera organon -> organa ottoman -> ottomans ought to be -> ought to be # VERB (UNLIKE bride to be) TODO:siverb overshoes -> overshoe TODO:siverb overtoes -> overtoe ovum -> ova ox -> oxen TODO:siadj ox's -> oxen's # POSSESSIVE FORM oxman -> oxmen oxymoron -> oxymorons|oxymora Panaman -> Panamans parabola -> parabolas|parabolae Parmese -> Parmese pathos -> pathoses pegasus -> pegasuses Pekingese -> Pekingese pelvis -> pelvises pendulum -> pendulums penis -> penises|penes penumbra -> penumbras|penumbrae perihelion -> perihelia person -> people|persons persona -> personae petroleum -> petroleums phalanx -> phalanxes|phalanges PhD -> PhDs phenomenon -> phenomena philtrum -> philtrums photo -> photos phylum -> phylums|phyla piano -> pianos|piani Piedmontese -> Piedmontese pika -> pikas TODO:singular_noun ret mul value pincer -> pincers pincers -> pincers Pistoiese -> Pistoiese plateau -> plateaus|plateaux play -> plays plexus -> plexuses|plexus pliers -> pliers plies -> ply # VERB FORM polis -> polises Polonese -> Polonese pontifex -> pontifexes|pontifices portmanteau -> portmanteaus|portmanteaux Portuguese -> Portuguese possum -> possums potato -> potatoes pox -> pox pragma -> pragmas|pragmata premium -> premiums prima donna -> prima donnas|prime donne pro -> pros proceedings -> proceedings prolegomenon -> prolegomena proof -> proofs proof of concept -> proofs of concept prosecutrix -> prosecutrixes|prosecutrices prospectus -> prospectuses|prospectus protozoan -> protozoans protozoon -> protozoa puma -> pumas TODO:siverb put -> put quantum -> quantums|quanta TODO:singular_noun quartermaster general -> quartermasters general quarto -> quartos quiz -> quizzes quizzes -> quiz # VERB FORM quorum -> quorums rabies -> rabies radius -> radiuses|radii radix -> radices ragman -> ragmen rebus -> rebuses TODO:siverb rehoes -> rehoe reindeer -> reindeer TODO:siverb reshoes -> reshoe rhino -> rhinos rhinoceros -> rhinoceroses|rhinoceros TODO:siverb roes -> roe Rom -> Roma Romagnese -> Romagnese Roman -> Romans Romanese -> Romanese Romany -> Romanies romeo -> romeos roof -> roofs rostrum -> rostrums|rostra ruckus -> ruckuses salmon -> salmon Sangirese -> Sangirese TODO: siverb sank -> sank Sarawakese -> Sarawakese sarcoma -> sarcomas|sarcomata sassafras -> sassafrases saw -> saw # VERB FORM (1st/2nd pers.) saw -> saws # NOUN FORM saws -> saw # VERB FORM (3rd pers.) scarf -> scarves schema -> schemas|schemata scissors -> scissors Scotsman -> Scotsmen sea-bass -> sea-bass seaman -> seamen self -> selves Selman -> Selmans Senegalese -> Senegalese seraph -> seraphs|seraphim series -> series TODO:siverb shall eat -> shall eat shaman -> shamans Shavese -> Shavese Shawanese -> Shawanese TODO:singular_noun multivalue she -> they sheaf -> sheaves shears -> shears sheep -> sheep shelf -> shelves TODO:siverb shoes -> shoe TODO:siverb should have -> should have Siamese -> Siamese siemens -> siemens Sienese -> Sienese Sikkimese -> Sikkimese silex -> silices simplex -> simplexes|simplices Singhalese -> Singhalese Sinhalese -> Sinhalese sinus -> sinuses|sinus size -> sizes sizes -> size #VERB FORM smallpox -> smallpox Smith -> Smiths TODO:siverb snowshoes -> snowshoe Sogdianese -> Sogdianese soliloquy -> soliloquies solo -> solos|soli soma -> somas|somata TODO:singular_noun tough son of a bitch -> sons of bitches Sonaman -> Sonamans soprano -> sopranos|soprani TODO:siverb sought -> sought TODO:siverb spattlehoes -> spattlehoe species -> species spectrum -> spectrums|spectra speculum -> speculums|specula TODO:siverb spent -> spent spermatozoon -> spermatozoa sphinx -> sphinxes|sphinges spokesperson -> spokespeople|spokespersons stadium -> stadiums|stadia stamen -> stamens|stamina status -> statuses|status stereo -> stereos stigma -> stigmas|stigmata stimulus -> stimuli stoma -> stomas|stomata stomach -> stomachs storey -> storeys story -> stories stratum -> strata strife -> strifes stylo -> stylos stylus -> styluses|styli succubus -> succubuses|succubi Sudanese -> Sudanese suffix -> suffixes Sundanese -> Sundanese superior -> superiors TODO:singular_noun Surgeon-General -> Surgeons-General surplus -> surpluses Swahilese -> Swahilese swine -> swines|swine TODO:singular_noun multiple return syringe -> syringes syrinx -> syrinxes|syringes tableau -> tableaus|tableaux taco -> tacos Tacoman -> Tacomans talouse -> talouses tattoo -> tattoos taxman -> taxmen tempo -> tempos|tempi Tenggerese -> Tenggerese testatrix -> testatrixes|testatrices testes -> testes TODO:singular_noun multiple return testis -> testes TODO:siadj that -> those TODO:siadj their -> their # POSSESSIVE FORM (GENDER-INCLUSIVE) TODO:singular_noun multiple return themself -> themselves # ugly but gaining currency TODO:singular_noun multiple return they -> they # for indeterminate gender thief -> thiefs|thieves TODO:siadj this -> these thought -> thoughts # NOUN FORM thought -> thought # VERB FORM TODO:siverb throes -> throe TODO:siverb ticktacktoes -> ticktacktoe Times -> Timeses Timorese -> Timorese TODO:siverb tiptoes -> tiptoe Tirolese -> Tirolese titmouse -> titmice TODO:singular_noun multivalue to her -> to them TODO:singular_noun multivalue to herself -> to themselves TODO:singular_noun multivalue to him -> to them TODO:singular_noun multivalue to himself -> to themselves to it -> to them to it -> to them # ACCUSATIVE to itself -> to themselves to me -> to us to myself -> to ourselves TODO:singular_noun multivalue to them -> to them # for indeterminate gender TODO:singular_noun multivalue to themself -> to themselves # ugly but gaining currency to you -> to you to yourself -> to yourselves Tocharese -> Tocharese TODO:siverb toes -> toe tomato -> tomatoes Tonkinese -> Tonkinese tonsillitis -> tonsillitises|tonsillitides tooth -> teeth Torinese -> Torinese torus -> toruses|tori trapezium -> trapeziums|trapezia trauma -> traumas|traumata travois -> travois trellis -> trellises TODO:siverb tries -> try trilby -> trilbys trousers -> trousers trousseau -> trousseaus|trousseaux trout -> trout TODO:siverb try -> tries tuna -> tuna turf -> turfs|turves Tyrolese -> Tyrolese ultimatum -> ultimatums|ultimata umbilicus -> umbilicuses|umbilici umbra -> umbras|umbrae TODO:siverb undershoes -> undershoe TODO:siverb unshoes -> unshoe uterus -> uteruses|uteri vacuum -> vacuums|vacua vellum -> vellums velum -> velums|vela Vermontese -> Vermontese Veronese -> Veronese vertebra -> vertebrae vertex -> vertexes|vertices Viennese -> Viennese Vietnamese -> Vietnamese virtuoso -> virtuosos|virtuosi virus -> viruses vixen -> vixens vortex -> vortexes|vortices walrus -> walruses TODO:siverb was -> were TODO:siverb was faced with -> were faced with TODO:siverb was hoping -> were hoping Wenchowese -> Wenchowese TODO:siverb were -> were TODO:siverb were found -> were found wharf -> wharves whiting -> whiting Whitmanese -> Whitmanese whiz -> whizzes TODO:singular_noun multivalue whizz -> whizzes widget -> widgets wife -> wives wildebeest -> wildebeests|wildebeest will -> will # VERB FORM will -> wills # NOUN FORM will eat -> will eat # VERB FORM wills -> will # VERB FORM wish -> wishes TODO:singular_noun multivalue with him -> with them with it -> with them # ACCUSATIVE TODO:siverb woes -> woe wolf -> wolves woman -> women woman of substance -> women of substance TODO:siadj woman's -> women's # POSSESSIVE FORM won't -> won't # VERB FORM woodlouse -> woodlice Yakiman -> Yakimans Yengeese -> Yengeese yeoman -> yeomen yeowoman -> yeowomen yes -> yeses Yokohaman -> Yokohamans you -> you TODO:siadj your -> your # POSSESSIVE FORM yourself -> yourselves Yuman -> Yumans Yunnanese -> Yunnanese zero -> zeros zoon -> zoa inflect-2.1.0/tests/test_an.py0000644000076500000240000000161313372337710016700 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_an(): p = inflect.engine() eq_(p.an("cat"), "a cat", msg="a cat") eq_(p.an("ant"), "an ant", msg="an ant") eq_(p.an("a"), "an a", msg="an a") eq_(p.an("b"), "a b", msg="a b") eq_(p.an("honest cat"), "an honest cat", msg="an honest") eq_(p.an("dishonest cat"), "a dishonest cat", msg="a dishonest") eq_(p.an("Honolulu sunset"), "a Honolulu sunset", msg="a Honolulu") eq_(p.an("mpeg"), "an mpeg", msg="an mpeg") eq_(p.an("onetime holiday"), "a onetime holiday", msg="a onetime") eq_(p.an("Ugandan person"), "a Ugandan person", msg="a Ugandan") eq_(p.an("Ukranian person"), "a Ukranian person", msg="a Ukranian") eq_(p.an("Unabomber"), "a Unabomber", msg="a Unabomber") eq_(p.an("unanimous decision"), "a unanimous decision", msg="a unanimous") eq_(p.an("US farmer"), "a US farmer", msg="a US") inflect-2.1.0/tests/test_classical_all.py0000644000076500000240000000644213372337710021075 0ustar jaracostaff00000000000000import unittest import inflect class test(unittest.TestCase): def test_classical(self): p = inflect.engine() # DEFAULT... self.assertEqual( p.plural_noun("error", 0), "errors", msg="classical 'zero' not active" ) self.assertEqual( p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active", ) self.assertEqual( p.plural_noun("Sally"), "Sallys", msg="classical 'names' active" ) self.assertEqual( p.plural_noun("brother"), "brothers", msg="classical others not active" ) self.assertEqual( p.plural_noun("person"), "people", msg="classical 'persons' not active" ) self.assertEqual( p.plural_noun("formula"), "formulas", msg="classical 'ancient' not active" ) # CLASSICAL PLURALS ACTIVATED... p.classical(all=True) self.assertEqual( p.plural_noun("error", 0), "error", msg="classical 'zero' active" ) self.assertEqual( p.plural_noun("wildebeest"), "wildebeest", msg="classical 'herd' active" ) self.assertEqual( p.plural_noun("Sally"), "Sallys", msg="classical 'names' active" ) self.assertEqual( p.plural_noun("brother"), "brethren", msg="classical others active" ) self.assertEqual( p.plural_noun("person"), "persons", msg="classical 'persons' active" ) self.assertEqual( p.plural_noun("formula"), "formulae", msg="classical 'ancient' active" ) # CLASSICAL PLURALS DEACTIVATED... p.classical(all=False) self.assertEqual( p.plural_noun("error", 0), "errors", msg="classical 'zero' not active" ) self.assertEqual( p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active", ) self.assertEqual( p.plural_noun("Sally"), "Sallies", msg="classical 'names' not active" ) self.assertEqual( p.plural_noun("brother"), "brothers", msg="classical others not active" ) self.assertEqual( p.plural_noun("person"), "people", msg="classical 'persons' not active" ) self.assertEqual( p.plural_noun("formula"), "formulas", msg="classical 'ancient' not active" ) # CLASSICAL PLURALS REREREACTIVATED... p.classical() self.assertEqual( p.plural_noun("error", 0), "error", msg="classical 'zero' active" ) self.assertEqual( p.plural_noun("wildebeest"), "wildebeest", msg="classical 'herd' active" ) self.assertEqual( p.plural_noun("Sally"), "Sallys", msg="classical 'names' active" ) self.assertEqual( p.plural_noun("brother"), "brethren", msg="classical others active" ) self.assertEqual( p.plural_noun("person"), "persons", msg="classical 'persons' active" ) self.assertEqual( p.plural_noun("formula"), "formulae", msg="classical 'ancient' active" ) if __name__ == "__main__": try: unittest.main() except SystemExit: pass inflect-2.1.0/tests/test_classical_ancient.py0000644000076500000240000000142313372337710021740 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' not active") # "person" PLURALS ACTIVATED... p.classical(ancient=True) eq_(p.plural_noun("formula"), "formulae", msg="classical 'ancient' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active") eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active") eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active") eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") inflect-2.1.0/tests/test_classical_herd.py0000644000076500000240000000141613372337710021243 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active") # "person" PLURALS ACTIVATED... p.classical(herd=True) eq_(p.plural_noun("wildebeest"), "wildebeest", msg="classical 'herd' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' active") eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active") eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active") eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") inflect-2.1.0/tests/test_classical_names.py0000644000076500000240000000164313372337710021426 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active") # "person" PLURALS ACTIVATED... p.classical(names=True) eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active") eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' active") eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active") eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active") eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") inflect-2.1.0/tests/test_classical_person.py0000644000076500000240000000153313372337710021627 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") # "person" PLURALS ACTIVATED... p.classical(persons=True) eq_(p.plural_noun("person"), "persons", msg="classical 'persons' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active") eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' active") eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active") eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active") eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active") inflect-2.1.0/tests/test_classical_zero.py0000644000076500000240000000140713372337710021300 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active") # "person" PLURALS ACTIVATED... p.classical(zero=True) eq_(p.plural_noun("error", 0), "error", msg="classical 'zero' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun("wildebeest"), "wildebeests", msg="classical 'herd' not active") eq_(p.plural_noun("formula"), "formulas", msg="classical 'ancient' active") eq_(p.plural_noun("person"), "people", msg="classical 'persons' not active") eq_(p.plural_noun("brother"), "brothers", msg="classical 'all' not active") eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") inflect-2.1.0/tests/test_compounds.py0000644000076500000240000000416313372337710020314 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect p = inflect.engine() def test_compound_1(): eq_(p.singular_noun("hello-out-there"), "hello-out-there") def test_compound_2(): eq_(p.singular_noun("hello out there"), "hello out there") def test_compound_3(): eq_(p.singular_noun("continue-to-operate"), "continue-to-operate") def test_compound_4(): eq_(p.singular_noun("case of diapers"), "case of diapers") def test_unit_handling_degree(): test_cases = { "degree celsius": "degrees celsius", # 'degree Celsius': 'degrees Celsius', "degree fahrenheit": "degrees fahrenheit", "degree rankine": "degrees rankine", "degree fahrenheit second": "degree fahrenheit seconds", } for singular, plural in test_cases.items(): eq_(p.plural(singular), plural) def test_unit_handling_fractional(): test_cases = { "pound per square inch": "pounds per square inch", "metre per second": "metres per second", "kilometre per hour": "kilometres per hour", "cubic metre per second": "cubic metres per second", "dollar a year": "dollars a year", # Correct pluralization of denominator "foot per square second": "feet per square second", "mother-in-law per lifetime": "mothers-in-law per lifetime", "pound-force per square inch": "pounds-force per square inch", } for singular, plural in test_cases.items(): eq_(p.plural(singular), plural) def test_unit_handling_combined(): test_cases = { # Heat transfer coefficient unit "watt per square meter degree celsius": "watts per square meter degree celsius", "degree celsius per hour": "degrees celsius per hour", "degree fahrenheit hour square foot per btuit inch": ( "degree fahrenheit hour square feet per btuit inch" ), # 'degree Celsius per hour': 'degrees Celsius per hour', # 'degree Fahrenheit hour square foot per BtuIT inch': # 'degree Fahrenheit hour square feet per BtuIT inch' } for singular, plural in test_cases.items(): eq_(p.plural(singular), plural) inflect-2.1.0/tests/test_inflections.py0000644000076500000240000002112213372337710020614 0ustar jaracostaff00000000000000import os import io import six from nose.tools import eq_, assert_not_equal, raises import inflect def is_eq(p, a, b): return ( p.compare(a, b) or p.plnounequal(a, b) or p.plverbequal(a, b) or p.pladjequal(a, b) ) def test_many(): p = inflect.engine() data = get_data() for line in data: if "TODO:" in line: continue try: singular, rest = line.split("->", 1) except ValueError: continue singular = singular.strip() rest = rest.strip() try: plural, comment = rest.split("#", 1) except ValueError: plural = rest.strip() comment = "" try: mod_plural, class_plural = plural.split("|", 1) mod_plural = mod_plural.strip() class_plural = class_plural.strip() except ValueError: mod_plural = class_plural = plural.strip() if "verb" in comment.lower(): is_nv = "_V" elif "noun" in comment.lower(): is_nv = "_N" else: is_nv = "" p.classical(all=0, names=0) mod_PL_V = p.plural_verb(singular) mod_PL_N = p.plural_noun(singular) mod_PL = p.plural(singular) if is_nv == "_V": mod_PL_val = mod_PL_V elif is_nv == "_N": mod_PL_val = mod_PL_N else: mod_PL_val = mod_PL p.classical(all=1) class_PL_V = p.plural_verb(singular) class_PL_N = p.plural_noun(singular) class_PL = p.plural(singular) if is_nv == "_V": class_PL_val = class_PL_V elif is_nv == "_N": class_PL_val = class_PL_N else: class_PL_val = class_PL check_all( p, is_nv, singular, mod_PL_val, class_PL_val, mod_plural, class_plural ) def check_all(p, is_nv, singular, mod_PL_val, class_PL_val, mod_plural, class_plural): eq_(mod_plural, mod_PL_val) eq_(class_plural, class_PL_val) eq_( is_eq(p, singular, mod_plural) in ("s:p", "p:s", "eq"), True, msg="is_eq({},{}) == {} != {}".format( singular, mod_plural, is_eq(p, singular, mod_plural), "s:p, p:s or eq" ), ) eq_( is_eq(p, mod_plural, singular) in ("p:s", "s:p", "eq"), True, msg="is_eq({},{}) == {} != {}".format( mod_plural, singular, is_eq(p, mod_plural, singular), "s:p, p:s or eq" ), ) eq_(is_eq(p, singular, class_plural) in ("s:p", "p:s", "eq"), True) eq_(is_eq(p, class_plural, singular) in ("p:s", "s:p", "eq"), True) assert_not_equal(singular, "") eq_(mod_PL_val, mod_PL_val if class_PL_val else "%s|%s"(mod_PL_val, class_PL_val)) if is_nv != "_V": eq_( p.singular_noun(mod_plural, 1), singular, msg="p.singular_noun({}) == {} != {}".format( mod_plural, p.singular_noun(mod_plural, 1), singular ), ) eq_( p.singular_noun(class_plural, 1), singular, msg="p.singular_noun({}) == {} != {}".format( class_plural, p.singular_noun(class_plural, 1), singular ), ) def test_def(): p = inflect.engine() p.defnoun("kin", "kine") p.defnoun("(.*)x", "$1xen") p.defverb("foobar", "feebar", "foobar", "feebar", "foobars", "feebar") p.defadj("red", "red|gules") eq_(p.no("kin", 0), "no kine", msg="kin -> kine (user defined)...") eq_(p.no("kin", 1), "1 kin") eq_(p.no("kin", 2), "2 kine") eq_(p.no("regex", 0), "no regexen", msg="regex -> regexen (user defined)") eq_(p.plural("foobar", 2), "feebar", msg="foobar -> feebar (user defined)...") eq_(p.plural("foobars", 2), "feebar") eq_(p.plural("red", 0), "red", msg="red -> red...") eq_(p.plural("red", 1), "red") eq_(p.plural("red", 2), "red") p.classical(all=True) eq_(p.plural("red", 0), "red", msg="red -> gules...") eq_(p.plural("red", 1), "red") eq_(p.plural("red", 2), "gules") def test_ordinal(): p = inflect.engine() eq_(p.ordinal(0), "0th", msg="0 -> 0th...") eq_(p.ordinal(1), "1st") eq_(p.ordinal(2), "2nd") eq_(p.ordinal(3), "3rd") eq_(p.ordinal(4), "4th") eq_(p.ordinal(5), "5th") eq_(p.ordinal(6), "6th") eq_(p.ordinal(7), "7th") eq_(p.ordinal(8), "8th") eq_(p.ordinal(9), "9th") eq_(p.ordinal(10), "10th") eq_(p.ordinal(11), "11th") eq_(p.ordinal(12), "12th") eq_(p.ordinal(13), "13th") eq_(p.ordinal(14), "14th") eq_(p.ordinal(15), "15th") eq_(p.ordinal(16), "16th") eq_(p.ordinal(17), "17th") eq_(p.ordinal(18), "18th") eq_(p.ordinal(19), "19th") eq_(p.ordinal(20), "20th") eq_(p.ordinal(21), "21st") eq_(p.ordinal(22), "22nd") eq_(p.ordinal(23), "23rd") eq_(p.ordinal(24), "24th") eq_(p.ordinal(100), "100th") eq_(p.ordinal(101), "101st") eq_(p.ordinal(102), "102nd") eq_(p.ordinal(103), "103rd") eq_(p.ordinal(104), "104th") eq_(p.ordinal("zero"), "zeroth", msg="zero -> zeroth...") eq_(p.ordinal("one"), "first") eq_(p.ordinal("two"), "second") eq_(p.ordinal("three"), "third") eq_(p.ordinal("four"), "fourth") eq_(p.ordinal("five"), "fifth") eq_(p.ordinal("six"), "sixth") eq_(p.ordinal("seven"), "seventh") eq_(p.ordinal("eight"), "eighth") eq_(p.ordinal("nine"), "ninth") eq_(p.ordinal("ten"), "tenth") eq_(p.ordinal("eleven"), "eleventh") eq_(p.ordinal("twelve"), "twelfth") eq_(p.ordinal("thirteen"), "thirteenth") eq_(p.ordinal("fourteen"), "fourteenth") eq_(p.ordinal("fifteen"), "fifteenth") eq_(p.ordinal("sixteen"), "sixteenth") eq_(p.ordinal("seventeen"), "seventeenth") eq_(p.ordinal("eighteen"), "eighteenth") eq_(p.ordinal("nineteen"), "nineteenth") eq_(p.ordinal("twenty"), "twentieth") eq_(p.ordinal("twenty-one"), "twenty-first") eq_(p.ordinal("twenty-two"), "twenty-second") eq_(p.ordinal("twenty-three"), "twenty-third") eq_(p.ordinal("twenty-four"), "twenty-fourth") eq_(p.ordinal("one hundred"), "one hundredth") eq_(p.ordinal("one hundred and one"), "one hundred and first") eq_(p.ordinal("one hundred and two"), "one hundred and second") eq_(p.ordinal("one hundred and three"), "one hundred and third") eq_(p.ordinal("one hundred and four"), "one hundred and fourth") def test_prespart(): p = inflect.engine() eq_(p.present_participle("sees"), "seeing", msg="sees -> seeing...") eq_(p.present_participle("eats"), "eating") eq_(p.present_participle("bats"), "batting") eq_(p.present_participle("hates"), "hating") eq_(p.present_participle("spies"), "spying") eq_(p.present_participle("skis"), "skiing") def test_inflect_on_tuples(): p = inflect.engine() eq_(p.inflect("plural('egg', ('a', 'b', 'c'))"), "eggs") eq_(p.inflect("plural('egg', ['a', 'b', 'c'])"), "eggs") eq_(p.inflect("plural_noun('egg', ('a', 'b', 'c'))"), "eggs") eq_(p.inflect("plural_adj('a', ('a', 'b', 'c'))"), "some") eq_(p.inflect("plural_verb('was', ('a', 'b', 'c'))"), "were") eq_(p.inflect("singular_noun('eggs', ('a', 'b', 'c'))"), "eggs") eq_(p.inflect("an('error', ('a', 'b', 'c'))"), "('a', 'b', 'c') error") eq_(p.inflect("This is not a function(name)"), "This is not a function(name)") def test_inflect_on_builtin_constants(): p = inflect.engine() eq_(p.inflect("Plural of False is plural('False')"), "Plural of False is Falses") eq_(p.inflect("num(%d, False) plural('False')" % 10), " Falses") eq_(p.inflect("plural('True')"), "Trues") eq_(p.inflect("num(%d, True) plural('False')" % 10), "10 Falses") eq_(p.inflect("num(%d, %r) plural('False')" % (10, True)), "10 Falses") eq_(p.inflect("plural('None')"), "Nones") eq_(p.inflect("num(%d, %r) plural('True')" % (10, None)), "10 Trues") def test_inflect_keyword_args(): p = inflect.engine() eq_( p.inflect("number_to_words(1234, andword='')"), "one thousand, two hundred thirty-four", ) eq_( p.inflect("number_to_words(1234, andword='plus')"), "one thousand, two hundred plus thirty-four", ) eq_( p.inflect("number_to_words('555_1202', group=1, zero='oh')"), "five, five, five, one, two, oh, two", ) @raises(NameError) def test_NameError_in_strings(): p = inflect.engine() eq_(p.inflect("plural('two')"), "twoes") p.inflect("plural(two)") def get_data(): filename = os.path.join(os.path.dirname(__file__), "inflections.txt") with io.open(filename) as strm: return list(map(six.text_type.strip, strm)) inflect-2.1.0/tests/test_join.py0000644000076500000240000000657613372337710017256 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_join(): p = inflect.engine() # Three words... words = "apple banana carrot".split() eq_(p.join(words), "apple, banana, and carrot", msg="plain 3 words") eq_( p.join(words, final_sep=""), "apple, banana and carrot", msg="3 words, no final sep", ) eq_( p.join(words, final_sep="..."), "apple, banana... and carrot", msg="3 words, different final sep", ) eq_( p.join(words, final_sep="...", conj=""), "apple, banana... carrot", msg="-->{} != {}<-- 3 words, different final sep, no conjunction".format( p.join(words, final_sep="...", conj=""), "apple, banana... carrot" ), ) eq_( p.join(words, conj="or"), "apple, banana, or carrot", msg="{} != {} 3 words, different conjunction".format( p.join(words, conj="or"), "apple, banana, or carrot" ), ) # Three words with semicolons... words = ("apple,fuji", "banana", "carrot") eq_( p.join(words), "apple,fuji; banana; and carrot", msg="{} != {}<-- comma-inclusive 3 words".format( p.join(words), "apple,fuji, banana; and carrot" ), ) eq_( p.join(words, final_sep=""), "apple,fuji; banana and carrot", msg='join({}) == "{}" != "{}"'.format( words, p.join(words, final_sep=""), "apple,fuji) banana and carrot" ), ) eq_( p.join(words, final_sep="..."), "apple,fuji; banana... and carrot", msg="comma-inclusive 3 words, different final sep", ) eq_( p.join(words, final_sep="...", conj=""), "apple,fuji; banana... carrot", msg="comma-inclusive 3 words, different final sep, no conjunction", ) eq_( p.join(words, conj="or"), "apple,fuji; banana; or carrot", msg="comma-inclusive 3 words, different conjunction", ) # Two words... words = ("apple", "carrot") eq_(p.join(words), "apple and carrot", msg="plain 2 words") eq_(p.join(words, final_sep=""), "apple and carrot", msg="2 words, no final sep") eq_( p.join(words, final_sep="..."), "apple and carrot", msg="2 words, different final sep", ) eq_( p.join(words, final_sep="...", conj=""), "apple carrot", msg="join({}, final_sep='...', conj='') == {} != {}".format( words, p.join(words, final_sep="...", conj=""), "apple carrot" ), ) eq_( p.join(words, final_sep="...", conj="", conj_spaced=False), "applecarrot", msg="join({}, final_sep='...', conj='') == {} != {}".format( words, p.join(words, final_sep="...", conj=""), "applecarrot" ), ) eq_( p.join(words, conj="or"), "apple or carrot", msg="2 words, different conjunction", ) # One word... words = ["carrot"] eq_(p.join(words), "carrot", msg="plain 1 word") eq_(p.join(words, final_sep=""), "carrot", msg="1 word, no final sep") eq_(p.join(words, final_sep="..."), "carrot", msg="1 word, different final sep") eq_( p.join(words, final_sep="...", conj=""), "carrot", msg="1 word, different final sep, no conjunction", ) eq_(p.join(words, conj="or"), "carrot", msg="1 word, different conjunction") inflect-2.1.0/tests/test_numwords.py0000644000076500000240000004063213372337710020164 0ustar jaracostaff00000000000000from nose.tools import eq_ import inflect def test_loop(): p = inflect.engine() for thresh in range(21): for n in range(21): threshed = p.number_to_words(n, threshold=thresh) numwords = p.number_to_words(n) if n <= thresh: eq_(numwords, threshed, msg="Wordified {} (<= {})".format(n, thresh)) else: # $threshed =~ s/\D//gxms; eq_( threshed, str(n), msg="p.number_to_words({}, thresold={}) == {} != {}".format( n, thresh, threshed, str(n) ), ) def test_lines(): p = inflect.engine() eq_(p.number_to_words(999, threshold=500), "999", msg=" 999 -> 999") eq_(p.number_to_words(1000, threshold=500), "1,000", msg="1000 -> 1,000") eq_(p.number_to_words(10000, threshold=500), "10,000", msg="10000 -> 10,000") eq_(p.number_to_words(100000, threshold=500), "100,000", msg="100000 -> 100,000") eq_( p.number_to_words(1000000, threshold=500), "1,000,000", msg="1000000 -> 1,000,000", ) eq_(p.number_to_words(999.3, threshold=500), "999.3", msg=" 999.3 -> 999.3") eq_(p.number_to_words(1000.3, threshold=500), "1,000.3", msg="1000.3 -> 1,000.3") eq_( p.number_to_words(10000.3, threshold=500), "10,000.3", msg="10000.3 -> 10,000.3" ) eq_( p.number_to_words(100000.3, threshold=500), "100,000.3", msg="100000.3 -> 100,000.3", ) eq_( p.number_to_words(1000000.3, threshold=500), "1,000,000.3", msg="1000000.3 -> 1,000,000.3", ) eq_(p.number_to_words(999, threshold=500, comma=0), "999", msg=" 999 -> 999") eq_(p.number_to_words(1000, threshold=500, comma=0), "1000", msg="1000 -> 1000") eq_(p.number_to_words(10000, threshold=500, comma=0), "10000", msg="10000 -> 10000") eq_( p.number_to_words(100000, threshold=500, comma=0), "100000", msg="100000 -> 100000", ) eq_( p.number_to_words(1000000, threshold=500, comma=0), "1000000", msg="1000000 -> 1000000", ) eq_( p.number_to_words(999.3, threshold=500, comma=0), "999.3", msg=" 999.3 -> 999.3" ) eq_( p.number_to_words(1000.3, threshold=500, comma=0), "1000.3", msg="1000.3 -> 1000.3", ) eq_( p.number_to_words(10000.3, threshold=500, comma=0), "10000.3", msg="10000.3 -> 10000.3", ) eq_( p.number_to_words(100000.3, threshold=500, comma=0), "100000.3", msg="100000.3 -> 100000.3", ) eq_( p.number_to_words(1000000.3, threshold=500, comma=0), "1000000.3", msg="1000000.3 -> 1000000.3", ) def test_array(): nw = [ ["0", "zero", "zero", "zero", "zero", "zeroth"], ["1", "one", "one", "one", "one", "first"], ["2", "two", "two", "two", "two", "second"], ["3", "three", "three", "three", "three", "third"], ["4", "four", "four", "four", "four", "fourth"], ["5", "five", "five", "five", "five", "fifth"], ["6", "six", "six", "six", "six", "sixth"], ["7", "seven", "seven", "seven", "seven", "seventh"], ["8", "eight", "eight", "eight", "eight", "eighth"], ["9", "nine", "nine", "nine", "nine", "ninth"], ["10", "ten", "one, zero", "ten", "ten", "tenth"], ["11", "eleven", "one, one", "eleven", "eleven", "eleventh"], ["12", "twelve", "one, two", "twelve", "twelve", "twelfth"], ["13", "thirteen", "one, three", "thirteen", "thirteen", "thirteenth"], ["14", "fourteen", "one, four", "fourteen", "fourteen", "fourteenth"], ["15", "fifteen", "one, five", "fifteen", "fifteen", "fifteenth"], ["16", "sixteen", "one, six", "sixteen", "sixteen", "sixteenth"], ["17", "seventeen", "one, seven", "seventeen", "seventeen", "seventeenth"], ["18", "eighteen", "one, eight", "eighteen", "eighteen", "eighteenth"], ["19", "nineteen", "one, nine", "nineteen", "nineteen", "nineteenth"], ["20", "twenty", "two, zero", "twenty", "twenty", "twentieth"], ["21", "twenty-one", "two, one", "twenty-one", "twenty-one", "twenty-first"], [ "29", "twenty-nine", "two, nine", "twenty-nine", "twenty-nine", "twenty-ninth", ], [ "99", "ninety-nine", "nine, nine", "ninety-nine", "ninety-nine", "ninety-ninth", ], [ "100", "one hundred", "one, zero, zero", "ten, zero", "one zero zero", "one hundredth", ], [ "101", "one hundred and one", "one, zero, one", "ten, one", "one zero one", "one hundred and first", ], [ "110", "one hundred and ten", "one, one, zero", "eleven, zero", "one ten", "one hundred and tenth", ], [ "111", "one hundred and eleven", "one, one, one", "eleven, one", "one eleven", "one hundred and eleventh", ], [ "900", "nine hundred", "nine, zero, zero", "ninety, zero", "nine zero zero", "nine hundredth", ], [ "999", "nine hundred and ninety-nine", "nine, nine, nine", "ninety-nine, nine", "nine ninety-nine", "nine hundred and ninety-ninth", ], [ "1000", "one thousand", "one, zero, zero, zero", "ten, zero zero", "one zero zero, zero", "one thousandth", ], [ "1001", "one thousand and one", "one, zero, zero, one", "ten, zero one", "one zero zero, one", "one thousand and first", ], [ "1010", "one thousand and ten", "one, zero, one, zero", "ten, ten", "one zero one, zero", "one thousand and tenth", ], [ "1100", "one thousand, one hundred", "one, one, zero, zero", "eleven, zero zero", "one ten, zero", "one thousand, one hundredth", ], [ "2000", "two thousand", "two, zero, zero, zero", "twenty, zero zero", "two zero zero, zero", "two thousandth", ], [ "10000", "ten thousand", "one, zero, zero, zero, zero", "ten, zero zero, zero", "one zero zero, zero zero", "ten thousandth", ], [ "100000", "one hundred thousand", "one, zero, zero, zero, zero, zero", "ten, zero zero, zero zero", "one zero zero, zero zero zero", "one hundred thousandth", ], [ "100001", "one hundred thousand and one", "one, zero, zero, zero, zero, one", "ten, zero zero, zero one", "one zero zero, zero zero one", "one hundred thousand and first", ], [ "123456", "one hundred and twenty-three thousand, " "four hundred and fifty-six", "one, two, three, four, five, six", "twelve, thirty-four, fifty-six", "one twenty-three, four fifty-six", "one hundred and twenty-three thousand, " "four hundred and fifty-sixth", ], [ "0123456", "one hundred and twenty-three thousand, " "four hundred and fifty-six", "zero, one, two, three, four, five, six", "zero one, twenty-three, forty-five, six", "zero twelve, three forty-five, six", "one hundred and twenty-three thousand, " "four hundred and fifty-sixth", ], [ "1234567", "one million, two hundred and thirty-four thousand, " "five hundred and sixty-seven", "one, two, three, four, five, six, seven", "twelve, thirty-four, fifty-six, seven", "one twenty-three, four fifty-six, seven", "one million, two hundred and thirty-four thousand, " "five hundred and sixty-seventh", ], [ "12345678", "twelve million, three hundred and forty-five thousand, " "six hundred and seventy-eight", "one, two, three, four, five, six, seven, eight", "twelve, thirty-four, fifty-six, seventy-eight", "one twenty-three, four fifty-six, seventy-eight", "twelve million, three hundred and forty-five thousand, " "six hundred and seventy-eighth", ], [ "12_345_678", "twelve million, three hundred and forty-five thousand, " "six hundred and seventy-eight", "one, two, three, four, five, six, seven, eight", "twelve, thirty-four, fifty-six, seventy-eight", "one twenty-three, four fifty-six, seventy-eight", ], [ "1234,5678", "twelve million, three hundred and forty-five thousand, " "six hundred and seventy-eight", "one, two, three, four, five, six, seven, eight", "twelve, thirty-four, fifty-six, seventy-eight", "one twenty-three, four fifty-six, seventy-eight", ], [ "1234567890", "one billion, two hundred and thirty-four million, five hundred " "and sixty-seven thousand, eight hundred and ninety", "one, two, three, four, five, six, seven, eight, nine, zero", "twelve, thirty-four, fifty-six, seventy-eight, ninety", "one twenty-three, four fifty-six, seven eighty-nine, zero", "one billion, two hundred and thirty-four million, five hundred " "and sixty-seven thousand, eight hundred and ninetieth", ], [ "123456789012345", "one hundred and twenty-three trillion, four hundred and " "fifty-six billion, seven hundred and eighty-nine million, twelve " "thousand, three hundred and forty-five", "one, two, three, four, five, six, seven, eight, nine, zero, one, " "two, three, four, five", "twelve, thirty-four, fifty-six, seventy-eight, ninety, twelve, " "thirty-four, five", "one twenty-three, four fifty-six, seven eighty-nine, " "zero twelve, three forty-five", "one hundred and twenty-three trillion, four hundred and " "fifty-six billion, seven hundred and eighty-nine million, " "twelve thousand, three hundred and forty-fifth", ], [ "12345678901234567890", "twelve quintillion, three hundred and forty-five quadrillion, " "six hundred and seventy-eight trillion, nine hundred and one " "billion, two hundred and thirty-four million, five hundred and " "sixty-seven thousand, eight hundred and ninety", "one, two, three, four, five, six, seven, eight, nine, zero, one, " "two, three, four, five, six, seven, eight, nine, zero", "twelve, thirty-four, fifty-six, seventy-eight, ninety, twelve, " "thirty-four, fifty-six, seventy-eight, ninety", "one twenty-three, four fifty-six, seven eighty-nine, " "zero twelve, three forty-five, six seventy-eight, ninety", "twelve quintillion, three hundred and forty-five quadrillion, " "six hundred and seventy-eight trillion, nine hundred and one " "billion, two hundred and thirty-four million, five hundred and " "sixty-seven thousand, eight hundred and ninetieth", ], [ "0.987654", "zero point nine eight seven six five four", "zero, point, nine, eight, seven, six, five, four", "zero, point, ninety-eight, seventy-six, fifty-four", "zero, point, nine eighty-seven, six fifty-four", "zeroth point nine eight seven six five four", "zero point nine eight seven six five fourth", ], [ ".987654", "point nine eight seven six five four", "point, nine, eight, seven, six, five, four", "point, ninety-eight, seventy-six, fifty-four", "point, nine eighty-seven, six fifty-four", "point nine eight seven six five four", "point nine eight seven six five fourth", ], [ "9.87654", "nine point eight seven six five four", "nine, point, eight, seven, six, five, four", "nine, point, eighty-seven, sixty-five, four", "nine, point, eight seventy-six, fifty-four", "ninth point eight seven six five four", "nine point eight seven six five fourth", ], [ "98.7654", "ninety-eight point seven six five four", "nine, eight, point, seven, six, five, four", "ninety-eight, point, seventy-six, fifty-four", "ninety-eight, point, seven sixty-five, four", "ninety-eighth point seven six five four", "ninety-eight point seven six five fourth", ], [ "987.654", "nine hundred and eighty-seven point six five four", "nine, eight, seven, point, six, five, four", "ninety-eight, seven, point, sixty-five, four", "nine eighty-seven, point, six fifty-four", "nine hundred and eighty-seventh point six five four", "nine hundred and eighty-seven point six five fourth", ], [ "9876.54", "nine thousand, eight hundred and seventy-six point five four", "nine, eight, seven, six, point, five, four", "ninety-eight, seventy-six, point, fifty-four", "nine eighty-seven, six, point, fifty-four", "nine thousand, eight hundred and seventy-sixth point five four", "nine thousand, eight hundred and seventy-six point five fourth", ], [ "98765.4", "ninety-eight thousand, seven hundred and sixty-five point four", "nine, eight, seven, six, five, point, four", "ninety-eight, seventy-six, five, point, four", "nine eighty-seven, sixty-five, point, four", "ninety-eight thousand, seven hundred and sixty-fifth point four", "ninety-eight thousand, seven hundred and sixty-five point fourth", ], [ "101.202.303", "one hundred and one point two zero two three zero three", "one, zero, one, point, two, zero, two, point, three, zero, three", "ten, one, point, twenty, two, point, thirty, three", "one zero one, point, two zero two, point, three zero three", ], [ "98765.", "ninety-eight thousand, seven hundred and sixty-five point", "nine, eight, seven, six, five, point", "ninety-eight, seventy-six, five, point", "nine eighty-seven, sixty-five, point", ], ] p = inflect.engine() for i in nw: go(p, i) def go(p, i): eq_( p.number_to_words(i[0]), i[1], msg="number_to_words({}) == {} != {}".format( i[0], p.number_to_words(i[0]), i[1] ), ) eq_(p.number_to_words(i[0], group=1), i[2]) eq_(p.number_to_words(i[0], group=2), i[3]) eq_(p.number_to_words(i[0], group=3), i[4]) if len(i) > 5: eq_( p.number_to_words(p.ordinal(i[0])), i[5], msg="number_to_words(ordinal({})) == {} != {}".format( i[0], p.number_to_words(p.ordinal(i[0])), i[5] ), ) if len(i) > 6: eq_(p.ordinal(p.number_to_words(i[0])), i[6]) else: if len(i) > 5: eq_(p.ordinal(p.number_to_words(i[0])), i[5]) # eq_ !eval { p.number_to_words(42, and=>); 1; }; # eq_ $@ =~ 'odd number of'; inflect-2.1.0/tests/test_pl_si.py0000644000076500000240000000252613372337710017414 0ustar jaracostaff00000000000000# use nosetest to run these tests from nose.tools import eq_ import inflect FNAME = "tests/words.txt" # FNAME = 'tests/list-of-nouns.txt' # FNAME = '/usr/share/dict/british-english' # FNAME = 'tricky.txt' def getwords(): words = open(FNAME).readlines() words = [w.strip() for w in words] return words def test_pl_si(): p = inflect.engine() words = getwords() for word in words: if word == "": continue if word[-2:] == "'s": continue # if word[-1] == 's': # continue p.classical(all=False) check_pl_si(p, word) p.classical(all=True) check_pl_si(p, word) def check_pl_si(p, word): if p.singular_noun(p.plural_noun(word, 2), 1) != word: f = open("badsi.txt", "a") f.write( "{} {} {}\n".format( word, p.plural_noun(word, 2), p.singular_noun(p.plural_noun(word, 2), 1) ) ) f.close() eq_( p.singular_noun(p.plural_noun(word, 2), 1), word, msg="""word==%s plnoun(%s)==%s sinoun(%s)==%s""" % ( word, word, p.plural_noun(word, 2), p.plural_noun(word, 2), p.singular_noun(p.plural_noun(word, 2), 1), ), ) inflect-2.1.0/tests/test_pwd.py0000644000076500000240000013044613372337710017103 0ustar jaracostaff00000000000000#!/usr/bin/python import unittest from inflect import ( BadChunkingOptionError, NumOutOfRangeError, BadNumValueError, BadGenderError, UnknownClassicalModeError, ) import inflect class test(unittest.TestCase): def TODO( self, ans, answer_wanted, answer_gives_now="default_that_will_never_occur__can't_use_None" "_as_that_is_a_possible_valid_value", ): """ make this test for future testing so can easily rename these to assertEqual when code ready """ if ans == answer_wanted: print("test unexpectedly passed!: {} == {}".format(ans, answer_wanted)) if answer_gives_now != ( "default_that_will_never_occur__can't_use_None" "_as_that_is_a_possible_valid_value" ): self.assertEqual(ans, answer_gives_now) def test_enclose(self): # def enclose self.assertEqual(inflect.enclose("test"), "(?:test)") def test_joinstem(self): # def joinstem self.assertEqual( inflect.joinstem(-2, ["ephemeris", "iris", ".*itis"]), "(?:ephemer|ir|.*it)" ) def test_classical(self): # classical dicts self.assertEqual( set(inflect.def_classical.keys()), set(inflect.all_classical.keys()) ) self.assertEqual( set(inflect.def_classical.keys()), set(inflect.no_classical.keys()) ) # def classical p = inflect.engine() self.assertEqual(p.classical_dict, inflect.def_classical) p.classical() self.assertEqual(p.classical_dict, inflect.all_classical) self.assertRaises(TypeError, p.classical, 0) self.assertRaises(TypeError, p.classical, 1) self.assertRaises(TypeError, p.classical, "names") self.assertRaises(TypeError, p.classical, "names", "zero") self.assertRaises(TypeError, p.classical, "all") p.classical(all=False) self.assertEqual(p.classical_dict, inflect.no_classical) p.classical(names=True, zero=True) mydict = inflect.def_classical.copy() mydict.update(dict(names=1, zero=1)) self.assertEqual(p.classical_dict, mydict) p.classical(all=True) self.assertEqual(p.classical_dict, inflect.all_classical) p.classical(all=False) p.classical(names=True, zero=True) mydict = inflect.def_classical.copy() mydict.update(dict(names=True, zero=True)) self.assertEqual(p.classical_dict, mydict) p.classical(all=False) p.classical(names=True, zero=False) mydict = inflect.def_classical.copy() mydict.update(dict(names=True, zero=False)) self.assertEqual(p.classical_dict, mydict) self.assertRaises(UnknownClassicalModeError, p.classical, bogus=True) def test_num(self): # def num p = inflect.engine() self.assertTrue(p.persistent_count is None) p.num() self.assertTrue(p.persistent_count is None) ret = p.num(3) self.assertEqual(p.persistent_count, 3) self.assertEqual(ret, "3") p.num() ret = p.num("3") self.assertEqual(p.persistent_count, 3) self.assertEqual(ret, "3") p.num() ret = p.num(count=3, show=1) self.assertEqual(p.persistent_count, 3) self.assertEqual(ret, "3") p.num() ret = p.num(count=3, show=0) self.assertEqual(p.persistent_count, 3) self.assertEqual(ret, "") self.assertRaises(BadNumValueError, p.num, "text") def test_inflect(self): p = inflect.engine() for txt, ans in ( ("num(1)", "1"), ("num(1,0)", ""), ("num(1,1)", "1"), ("num(1) ", "1 "), (" num(1) ", " 1 "), ("num(3) num(1)", "3 1"), ): self.assertEqual( p.inflect(txt), ans, msg='p.inflect("{}") != "{}"'.format(txt, ans) ) for txt, ans in ( ("plural('rock')", "rocks"), ("plural('rock') plural('child')", "rocks children"), ("num(2) plural('rock') plural('child')", "2 rocks children"), ( "plural('rock') plural_noun('rock') plural_verb('rocks') " "plural_adj('big') a('ant')", "rocks rocks rock big an ant", ), ( "an('rock') no('cat') ordinal(3) number_to_words(1234) " "present_participle('runs')", "a rock no cats 3rd one thousand, two hundred and thirty-four running", ), ("a('cat',0) a('cat',1) a('cat',2) a('cat', 2)", "0 cat a cat 2 cat 2 cat"), ): self.assertEqual( p.inflect(txt), ans, msg='p.inflect("{}") != "{}"'.format(txt, ans) ) def test_user_input_fns(self): p = inflect.engine() self.assertEqual(p.pl_sb_user_defined, []) p.defnoun("VAX", "VAXen") self.assertEqual(p.plural("VAX"), "VAXEN") self.assertEqual(p.pl_sb_user_defined, ["VAX", "VAXen"]) self.assertTrue(p.ud_match("word", p.pl_sb_user_defined) is None) self.assertEqual(p.ud_match("VAX", p.pl_sb_user_defined), "VAXen") self.assertTrue(p.ud_match("VVAX", p.pl_sb_user_defined) is None) p.defnoun("cow", "cows|kine") self.assertEqual(p.plural("cow"), "cows") p.classical() self.assertEqual(p.plural("cow"), "kine") self.assertEqual(p.ud_match("cow", p.pl_sb_user_defined), "cows|kine") p.defnoun("(.+i)o", r"$1i") self.assertEqual(p.plural("studio"), "studii") self.assertEqual(p.ud_match("studio", p.pl_sb_user_defined), "studii") p.defnoun("aviatrix", "aviatrices") self.assertEqual(p.plural("aviatrix"), "aviatrices") self.assertEqual(p.ud_match("aviatrix", p.pl_sb_user_defined), "aviatrices") p.defnoun("aviatrix", "aviatrixes") self.assertEqual(p.plural("aviatrix"), "aviatrixes") self.assertEqual(p.ud_match("aviatrix", p.pl_sb_user_defined), "aviatrixes") p.defnoun("aviatrix", None) self.assertEqual(p.plural("aviatrix"), "aviatrices") self.assertEqual(p.ud_match("aviatrix", p.pl_sb_user_defined), None) p.defnoun("(cat)", r"$1s") self.assertEqual(p.plural("cat"), "cats") inflect.STDOUT_ON = False self.assertRaises(inflect.BadUserDefinedPatternError, p.defnoun, "(??", None) inflect.STDOUT_ON = True p.defnoun(None, "") # check None doesn't crash it # defverb p.defverb("will", "shall", "will", "will", "will", "will") self.assertEqual(p.ud_match("will", p.pl_v_user_defined), "will") self.assertEqual(p.plural("will"), "will") # TODO: will -> shall. Tests below fail self.TODO(p.compare("will", "shall"), "s:p") self.TODO(p.compare_verbs("will", "shall"), "s:p") # defadj p.defadj("hir", "their") self.assertEqual(p.plural("hir"), "their") self.assertEqual(p.ud_match("hir", p.pl_adj_user_defined), "their") # defa defan p.defa("h") self.assertEqual(p.a("h"), "a h") self.assertEqual(p.ud_match("h", p.A_a_user_defined), "a") p.defan("horrendous.*") self.assertEqual(p.a("horrendously"), "an horrendously") self.assertEqual(p.ud_match("horrendously", p.A_a_user_defined), "an") def test_postprocess(self): p = inflect.engine() for orig, infl, txt in ( ("cow", "cows", "cows"), ("I", "we", "we"), ("COW", "cows", "COWS"), ("Cow", "cows", "Cows"), ("cow", "cows|kine", "cows"), ("Entry", "entries", "Entries"), ("can of Coke", "cans of coke", "cans of Coke"), ): self.assertEqual(p.postprocess(orig, infl), txt) p.classical() self.assertEqual(p.postprocess("cow", "cows|kine"), "kine") def test_partition_word(self): p = inflect.engine() for txt, part in ( (" cow ", (" ", "cow", " ")), ("cow", ("", "cow", "")), (" cow", (" ", "cow", "")), ("cow ", ("", "cow", " ")), (" cow ", (" ", "cow", " ")), ("", ("", "", "")), ("bottle of beer", ("", "bottle of beer", "")), # spaces give weird results # (' '),('', ' ', '')), # (' '),(' ', ' ', '')), # (' '),(' ', ' ', '')), ): self.assertEqual(p.partition_word(txt), part) def test_pl(self): p = inflect.engine() for fn, sing, plur in ( (p.plural, "", ""), (p.plural, "cow", "cows"), (p.plural, "thought", "thoughts"), (p.plural, "mouse", "mice"), (p.plural, "knife", "knives"), (p.plural, "knifes", "knife"), (p.plural, " cat ", " cats "), (p.plural, "court martial", "courts martial"), (p.plural, "a", "some"), (p.plural, "carmen", "carmina"), (p.plural, "quartz", "quartzes"), (p.plural, "care", "cares"), (p.plural_noun, "", ""), (p.plural_noun, "cow", "cows"), (p.plural_noun, "thought", "thoughts"), (p.plural_noun, "snooze", "snoozes"), (p.plural_verb, "", ""), (p.plural_verb, "runs", "run"), (p.plural_verb, "thought", "thought"), (p.plural_verb, "eyes", "eye"), (p.plural_adj, "", ""), (p.plural_adj, "a", "some"), (p.plural_adj, "this", "these"), (p.plural_adj, "that", "those"), (p.plural_adj, "my", "our"), (p.plural_adj, "cat's", "cats'"), (p.plural_adj, "child's", "children's"), ): self.assertEqual( fn(sing), plur, msg='{}("{}") == "{}" != "{}"'.format( fn.__name__, sing, fn(sing), plur ), ) for sing, num, plur in ( ("cow", 1, "cow"), ("cow", 2, "cows"), ("cow", "one", "cow"), ("cow", "each", "cow"), ("cow", "two", "cows"), ("cow", 0, "cows"), ("cow", "zero", "cows"), ("runs", 0, "run"), ("runs", 1, "runs"), ("am", 0, "are"), ): self.assertEqual(p.plural(sing, num), plur) p.classical(zero=True) self.assertEqual(p.plural("cow", 0), "cow") self.assertEqual(p.plural("cow", "zero"), "cow") self.assertEqual(p.plural("runs", 0), "runs") self.assertEqual(p.plural("am", 0), "am") self.assertEqual(p.plural_verb("runs", 1), "runs") self.assertEqual(p.plural("die"), "dice") self.assertEqual(p.plural_noun("die"), "dice") def test_sinoun(self): p = inflect.engine() for sing, plur in ( ("cat", "cats"), ("die", "dice"), ("status", "status"), ("hiatus", "hiatus"), ("goose", "geese"), ): self.assertEqual(p.singular_noun(plur), sing) self.assertEqual(p.inflect("singular_noun('%s')" % plur), sing) self.assertEqual(p.singular_noun("cats", count=2), "cats") self.assertEqual(p.singular_noun("zombies"), "zombie") self.assertEqual(p.singular_noun("shoes"), "shoe") self.assertEqual(p.singular_noun("Matisses"), "Matisse") self.assertEqual(p.singular_noun("bouillabaisses"), "bouillabaisse") self.assertEqual(p.singular_noun("quartzes"), "quartz") self.assertEqual(p.singular_noun("Nietzsches"), "Nietzsche") self.assertEqual(p.singular_noun("aches"), "ache") self.assertEqual(p.singular_noun("Clives"), "Clive") self.assertEqual(p.singular_noun("weaves"), "weave") def test_gender(self): p = inflect.engine() p.gender("feminine") for sing, plur in ( ("she", "they"), ("herself", "themselves"), ("hers", "theirs"), ("to her", "to them"), ("to herself", "to themselves"), ): self.assertEqual( p.singular_noun(plur), sing, "singular_noun({}) == {} != {}".format( plur, p.singular_noun(plur), sing ), ) self.assertEqual(p.inflect("singular_noun('%s')" % plur), sing) p.gender("masculine") for sing, plur in ( ("he", "they"), ("himself", "themselves"), ("his", "theirs"), ("to him", "to them"), ("to himself", "to themselves"), ): self.assertEqual( p.singular_noun(plur), sing, "singular_noun({}) == {} != {}".format( plur, p.singular_noun(plur), sing ), ) self.assertEqual(p.inflect("singular_noun('%s')" % plur), sing) p.gender("gender-neutral") for sing, plur in ( ("they", "they"), ("themself", "themselves"), ("theirs", "theirs"), ("to them", "to them"), ("to themself", "to themselves"), ): self.assertEqual( p.singular_noun(plur), sing, "singular_noun({}) == {} != {}".format( plur, p.singular_noun(plur), sing ), ) self.assertEqual(p.inflect("singular_noun('%s')" % plur), sing) p.gender("neuter") for sing, plur in ( ("it", "they"), ("itself", "themselves"), ("its", "theirs"), ("to it", "to them"), ("to itself", "to themselves"), ): self.assertEqual( p.singular_noun(plur), sing, "singular_noun({}) == {} != {}".format( plur, p.singular_noun(plur), sing ), ) self.assertEqual(p.inflect("singular_noun('%s')" % plur), sing) self.assertRaises(BadGenderError, p.gender, "male") for sing, plur, gen in ( ("it", "they", "neuter"), ("she", "they", "feminine"), ("he", "they", "masculine"), ("they", "they", "gender-neutral"), ("she or he", "they", "feminine or masculine"), ("he or she", "they", "masculine or feminine"), ): self.assertEqual(p.singular_noun(plur, gender=gen), sing) with self.assertRaises(BadGenderError): p.singular_noun("cats", gender="unknown gender") def test_plequal(self): p = inflect.engine() for fn, sing, plur, res in ( (p.compare, "index", "index", "eq"), (p.compare, "index", "indexes", "s:p"), (p.compare, "index", "indices", "s:p"), (p.compare, "indexes", "index", "p:s"), (p.compare, "indices", "index", "p:s"), (p.compare, "indices", "indexes", "p:p"), (p.compare, "indexes", "indices", "p:p"), (p.compare, "indices", "indices", "eq"), (p.compare, "opuses", "opera", "p:p"), (p.compare, "opera", "opuses", "p:p"), (p.compare, "brothers", "brethren", "p:p"), (p.compare, "cats", "cats", "eq"), (p.compare, "base", "basis", False), (p.compare, "syrinx", "syringe", False), (p.compare, "she", "he", False), (p.compare, "opus", "operas", False), (p.compare, "taxi", "taxes", False), (p.compare, "time", "Times", False), (p.compare, "time".lower(), "Times".lower(), "s:p"), (p.compare, "courts martial", "court martial", "p:s"), (p.compare, "my", "my", "eq"), (p.compare, "my", "our", "s:p"), (p.compare, "our", "our", "eq"), (p.compare_nouns, "index", "index", "eq"), (p.compare_nouns, "index", "indexes", "s:p"), (p.compare_nouns, "index", "indices", "s:p"), (p.compare_nouns, "indexes", "index", "p:s"), (p.compare_nouns, "indices", "index", "p:s"), (p.compare_nouns, "indices", "indexes", "p:p"), (p.compare_nouns, "indexes", "indices", "p:p"), (p.compare_nouns, "indices", "indices", "eq"), (p.compare_verbs, "runs", "runs", "eq"), (p.compare_verbs, "runs", "run", "s:p"), (p.compare_verbs, "run", "run", "eq"), (p.compare_adjs, "my", "my", "eq"), (p.compare_adjs, "my", "our", "s:p"), (p.compare_adjs, "our", "our", "eq"), ): self.assertEqual(fn(sing, plur), res) for fn, sing, plur, res, badres in ( ( p.compare, "dresses's", "dresses'", "p:p", "p:s", ), # TODO: should return p:p ( p.compare_adjs, "dresses's", "dresses'", "p:p", False, ), # TODO: should return p:p # TODO: future: support different singulars one day. (p.compare, "dress's", "dress'", "s:s", "p:s"), (p.compare_adjs, "dress's", "dress'", "s:s", False), (p.compare, "Jess's", "Jess'", "s:s", "p:s"), (p.compare_adjs, "Jess's", "Jess'", "s:s", False), ): self.TODO(fn(sing, plur), res, badres) # TODO: pass upstream. multiple adjective plurals not supported self.assertEqual(p.compare("your", "our"), False) p.defadj("my", "our|your") # what's ours is yours self.TODO(p.compare("your", "our"), "p:p") def test__pl_reg_plurals(self): p = inflect.engine() for pair, stems, end1, end2, ans in ( ("indexes|indices", "dummy|ind", "exes", "ices", True), ("indexes|robots", "dummy|ind", "exes", "ices", False), ("beaus|beaux", ".*eau", "s", "x", True), ): self.assertEqual(p._pl_reg_plurals(pair, stems, end1, end2), ans) def test__pl_check_plurals_N(self): p = inflect.engine() self.assertEqual(p._pl_check_plurals_N("index", "indices"), False) self.assertEqual(p._pl_check_plurals_N("indexes", "indices"), True) self.assertEqual(p._pl_check_plurals_N("indices", "indexes"), True) self.assertEqual(p._pl_check_plurals_N("stigmata", "stigmas"), True) self.assertEqual(p._pl_check_plurals_N("phalanxes", "phalanges"), True) def test__pl_check_plurals_adj(self): p = inflect.engine() self.assertEqual(p._pl_check_plurals_adj("indexes's", "indices's"), True) self.assertEqual(p._pl_check_plurals_adj("indices's", "indexes's"), True) self.assertEqual(p._pl_check_plurals_adj("indexes'", "indices's"), True) self.assertEqual(p._pl_check_plurals_adj("indexes's", "indices'"), True) self.assertEqual(p._pl_check_plurals_adj("indexes's", "indexes's"), False) self.assertEqual(p._pl_check_plurals_adj("dogmas's", "dogmata's"), True) self.assertEqual(p._pl_check_plurals_adj("dogmas'", "dogmata'"), True) self.assertEqual(p._pl_check_plurals_adj("indexes'", "indices'"), True) def test_count(self): p = inflect.engine() for txt, num in ( (1, 1), (2, 2), (0, 2), (87, 2), (-7, 2), ("1", 1), ("2", 2), ("0", 2), ("no", 2), ("zero", 2), ("nil", 2), ("a", 1), ("an", 1), ("one", 1), ("each", 1), ("every", 1), ("this", 1), ("that", 1), ("dummy", 2), ): self.assertEqual(p.get_count(txt), num) self.assertEqual(p.get_count(), "") p.num(3) self.assertEqual(p.get_count(), 2) def test__plnoun(self): p = inflect.engine() for sing, plur in ( ("", ""), ("tuna", "tuna"), ("TUNA", "TUNA"), ("swordfish", "swordfish"), ("Governor General", "Governors General"), ("Governor-General", "Governors-General"), ("Major General", "Major Generals"), ("Major-General", "Major-Generals"), ("mother in law", "mothers in law"), ("mother-in-law", "mothers-in-law"), ("about me", "about us"), ("to it", "to them"), ("from it", "from them"), ("with it", "with them"), ("I", "we"), ("you", "you"), ("me", "us"), ("mine", "ours"), ("child", "children"), ("brainchild", "brainchilds"), ("human", "humans"), ("soliloquy", "soliloquies"), ("chairwoman", "chairwomen"), ("goose", "geese"), ("tooth", "teeth"), ("foot", "feet"), ("forceps", "forceps"), ("protozoon", "protozoa"), ("czech", "czechs"), ("codex", "codices"), ("radix", "radices"), ("bacterium", "bacteria"), ("alumnus", "alumni"), ("criterion", "criteria"), ("alumna", "alumnae"), ("bias", "biases"), ("quiz", "quizzes"), ("fox", "foxes"), ("shelf", "shelves"), ("leaf", "leaves"), ("midwife", "midwives"), ("scarf", "scarves"), ("key", "keys"), ("Sally", "Sallys"), ("sally", "sallies"), ("ado", "ados"), ("auto", "autos"), ("alto", "altos"), ("zoo", "zoos"), ("tomato", "tomatoes"), ): self.assertEqual( p._plnoun(sing), plur, msg='p._plnoun("{}") == {} != "{}"'.format(sing, p._plnoun(sing), plur), ) self.assertEqual( p._sinoun(plur), sing, msg='p._sinoun("{}") != "{}"'.format(plur, sing) ) # words where forming singular is ambiguious or not attempted for sing, plur in ( ("son of a gun", "sons of guns"), ("son-of-a-gun", "sons-of-guns"), ("basis", "bases"), ("Jess", "Jesses"), ): self.assertEqual( p._plnoun(sing), plur, msg='p._plnoun("{}") != "{}"'.format(sing, plur) ) for sing, plur in ( # TODO: does not keep case ("about ME", "about US"), # TODO: does not keep case ("YOU", "YOU"), ): self.TODO(p._plnoun(sing), plur) p.num(1) self.assertEqual(p._plnoun("cat"), "cat") p.num(3) p.classical(herd=True) self.assertEqual(p._plnoun("swine"), "swine") p.classical(herd=False) self.assertEqual(p._plnoun("swine"), "swines") p.classical(persons=True) self.assertEqual(p._plnoun("chairperson"), "chairpersons") p.classical(persons=False) self.assertEqual(p._plnoun("chairperson"), "chairpeople") p.classical(ancient=True) self.assertEqual(p._plnoun("formula"), "formulae") p.classical(ancient=False) self.assertEqual(p._plnoun("formula"), "formulas") p.classical() for sing, plur in ( ("matrix", "matrices"), ("gateau", "gateaux"), ("millieu", "millieux"), ("syrinx", "syringes"), ("stamen", "stamina"), ("apex", "apices"), ("appendix", "appendices"), ("maximum", "maxima"), ("focus", "foci"), ("status", "status"), ("aurora", "aurorae"), ("soma", "somata"), ("iris", "irides"), ("solo", "soli"), ("oxymoron", "oxymora"), ("goy", "goyim"), ("afrit", "afriti"), ): self.assertEqual(p._plnoun(sing), plur) # p.classical(0) # p.classical('names') # clasical now back to the default mode def test_classical_pl(self): p = inflect.engine() p.classical() for sing, plur in (("brother", "brethren"), ("dogma", "dogmata")): self.assertEqual(p.plural(sing), plur) def test__pl_special_verb(self): p = inflect.engine() self.assertEqual(p._pl_special_verb(""), False) self.assertEqual(p._pl_special_verb("am"), "are") self.assertEqual(p._pl_special_verb("am", 0), "are") self.assertEqual(p._pl_special_verb("runs", 0), "run") p.classical(zero=True) self.assertEqual(p._pl_special_verb("am", 0), False) self.assertEqual(p._pl_special_verb("am", 1), "am") self.assertEqual(p._pl_special_verb("am", 2), "are") self.assertEqual(p._pl_special_verb("runs", 0), False) self.assertEqual(p._pl_special_verb("am going to"), "are going to") self.assertEqual(p._pl_special_verb("did"), "did") self.assertEqual(p._pl_special_verb("wasn't"), "weren't") self.assertEqual(p._pl_special_verb("shouldn't"), "shouldn't") self.assertEqual(p._pl_special_verb("bias"), False) self.assertEqual(p._pl_special_verb("news"), False) self.assertEqual(p._pl_special_verb("Jess"), False) self.assertEqual(p._pl_special_verb(" "), False) self.assertEqual(p._pl_special_verb("brushes"), "brush") self.assertEqual(p._pl_special_verb("fixes"), "fix") self.assertEqual(p._pl_special_verb("quizzes"), "quiz") self.assertEqual(p._pl_special_verb("fizzes"), "fizz") self.assertEqual(p._pl_special_verb("dresses"), "dress") self.assertEqual(p._pl_special_verb("flies"), "fly") self.assertEqual(p._pl_special_verb("canoes"), "canoe") self.assertEqual(p._pl_special_verb("horseshoes"), "horseshoe") self.assertEqual(p._pl_special_verb("does"), "do") # TODO: what's a real word to test this case? self.assertEqual(p._pl_special_verb("zzzoes"), "zzzo") self.assertEqual(p._pl_special_verb("runs"), "run") def test__pl_general_verb(self): p = inflect.engine() self.assertEqual(p._pl_general_verb("acts"), "act") self.assertEqual(p._pl_general_verb("act"), "act") self.assertEqual(p._pl_general_verb("saw"), "saw") self.assertEqual(p._pl_general_verb("runs", 1), "runs") def test__pl_special_adjective(self): p = inflect.engine() self.assertEqual(p._pl_special_adjective("a"), "some") self.assertEqual(p._pl_special_adjective("my"), "our") self.assertEqual(p._pl_special_adjective("John's"), "Johns'") # TODO: original can't handle this. should we handle it? self.TODO(p._pl_special_adjective("JOHN's"), "JOHNS'") # TODO: can't handle capitals self.TODO(p._pl_special_adjective("JOHN'S"), "JOHNS'") self.TODO(p._pl_special_adjective("TUNA'S"), "TUNA'S") self.assertEqual(p._pl_special_adjective("tuna's"), "tuna's") self.assertEqual(p._pl_special_adjective("TUNA's"), "TUNA's") self.assertEqual(p._pl_special_adjective("bad"), False) def test_a(self): p = inflect.engine() for sing, plur in ( ("cat", "a cat"), ("euphemism", "a euphemism"), ("Euler number", "an Euler number"), ("hour", "an hour"), ("houri", "a houri"), ("nth", "an nth"), ("rth", "an rth"), ("sth", "an sth"), ("xth", "an xth"), ("ant", "an ant"), ("book", "a book"), ("RSPCA", "an RSPCA"), ("SONAR", "a SONAR"), ("FJO", "a FJO"), ("FJ", "an FJ"), ("NASA", "a NASA"), ("UN", "a UN"), ("yak", "a yak"), ("yttrium", "an yttrium"), ("a elephant", "an elephant"), ("a giraffe", "a giraffe"), ("an ewe", "a ewe"), ("a orangutan", "an orangutan"), ("R.I.P.", "an R.I.P."), ("C.O.D.", "a C.O.D."), ("e-mail", "an e-mail"), ("X-ray", "an X-ray"), ("T-square", "a T-square"), ("LCD", "an LCD"), ("XML", "an XML"), ("YWCA", "a YWCA"), ("LED", "a LED"), ("OPEC", "an OPEC"), ("FAQ", "a FAQ"), ("UNESCO", "a UNESCO"), ("a", "an a"), ("an", "an an"), ("an ant", "an ant"), ("a cat", "a cat"), ("an cat", "a cat"), ("a ant", "an ant"), ): self.assertEqual(p.a(sing), plur) self.assertEqual(p.a("cat", 1), "a cat") self.assertEqual(p.a("cat", 2), "2 cat") self.assertEqual(p.a, p.an) self.assertEqual(p.a(""), "") def test_no(self): p = inflect.engine() self.assertEqual(p.no("cat"), "no cats") self.assertEqual(p.no("cat", count=3), "3 cats") self.assertEqual(p.no("cat", count="three"), "three cats") self.assertEqual(p.no("cat", count=1), "1 cat") self.assertEqual(p.no("cat", count="one"), "one cat") self.assertEqual(p.no("mouse"), "no mice") p.num(3) self.assertEqual(p.no("cat"), "3 cats") def test_prespart(self): p = inflect.engine() for sing, plur in ( ("runs", "running"), ("dies", "dying"), ("glues", "gluing"), ("eyes", "eying"), ("skis", "skiing"), ("names", "naming"), ("sees", "seeing"), ("hammers", "hammering"), ("bats", "batting"), ("eats", "eating"), ("loves", "loving"), ("spies", "spying"), ): self.assertEqual(p.present_participle(sing), plur) self.assertEqual(p.present_participle("hoes"), "hoeing") self.assertEqual(p.present_participle("alibis"), "alibiing") self.assertEqual(p.present_participle("is"), "being") self.assertEqual(p.present_participle("are"), "being") self.assertEqual(p.present_participle("had"), "having") self.assertEqual(p.present_participle("has"), "having") def test_ordinal(self): p = inflect.engine() for num, numord in ( ("1", "1st"), ("2", "2nd"), ("3", "3rd"), ("4", "4th"), ("10", "10th"), ("28", "28th"), ("100", "100th"), ("101", "101st"), ("1000", "1000th"), ("1001", "1001st"), ("0", "0th"), ("one", "first"), ("two", "second"), ("four", "fourth"), ("twenty", "twentieth"), ("one hundered", "one hunderedth"), ("one hundered and one", "one hundered and first"), ("zero", "zeroth"), ("n", "nth"), # bonus! ): self.assertEqual(p.ordinal(num), numord) def test_millfn(self): p = inflect.engine() millfn = p.millfn self.assertEqual(millfn(1), " thousand") self.assertEqual(millfn(2), " million") self.assertEqual(millfn(3), " billion") self.assertEqual(millfn(0), " ") self.assertEqual(millfn(11), " decillion") inflect.STDOUT_ON = False self.assertRaises(NumOutOfRangeError, millfn, 12) inflect.STDOUT_ON = True def test_unitfn(self): p = inflect.engine() unitfn = p.unitfn self.assertEqual(unitfn(1, 2), "one million") self.assertEqual(unitfn(1, 3), "one billion") self.assertEqual(unitfn(5, 3), "five billion") self.assertEqual(unitfn(5, 0), "five ") self.assertEqual(unitfn(0, 0), " ") def test_tenfn(self): p = inflect.engine() tenfn = p.tenfn self.assertEqual(tenfn(3, 1, 2), "thirty-one million") self.assertEqual(tenfn(3, 0, 2), "thirty million") self.assertEqual(tenfn(0, 1, 2), "one million") self.assertEqual(tenfn(1, 1, 2), "eleven million") self.assertEqual(tenfn(1, 0, 2), "ten million") self.assertEqual(tenfn(1, 0, 0), "ten ") self.assertEqual(tenfn(0, 0, 0), " ") def test_hundfn(self): p = inflect.engine() hundfn = p.hundfn p.number_args = dict(andword="and") self.assertEqual(hundfn(4, 3, 1, 2), "four hundred and thirty-one million, ") self.assertEqual(hundfn(4, 0, 0, 2), "four hundred million, ") self.assertEqual(hundfn(4, 0, 5, 2), "four hundred and five million, ") self.assertEqual(hundfn(0, 3, 1, 2), "thirty-one million, ") self.assertEqual(hundfn(0, 0, 7, 2), "seven million, ") def test_enword(self): p = inflect.engine() enword = p.enword self.assertEqual(enword("5", 1), "five, ") p.number_args = dict(zero="zero", one="one", andword="and") self.assertEqual(enword("0", 1), " zero, ") self.assertEqual(enword("1", 1), " one, ") self.assertEqual(enword("347", 1), "three, four, seven, ") self.assertEqual(enword("34", 2), "thirty-four , ") self.assertEqual(enword("347", 2), "thirty-four , seven, ") self.assertEqual(enword("34768", 2), "thirty-four , seventy-six , eight, ") self.assertEqual(enword("1", 2), "one, ") p.number_args["one"] = "single" self.TODO( enword("1", 2), "single, ", "one, " ) # TODO: doesn't use default word for 'one' here p.number_args["one"] = "one" self.assertEqual(enword("134", 3), " one thirty-four , ") self.assertEqual(enword("0", -1), "zero") self.assertEqual(enword("1", -1), "one") self.assertEqual(enword("3", -1), "three , ") self.assertEqual(enword("12", -1), "twelve , ") self.assertEqual(enword("123", -1), "one hundred and twenty-three , ") self.assertEqual( enword("1234", -1), "one thousand, two hundred and thirty-four , " ) self.assertEqual( enword("12345", -1), "twelve thousand, three hundred and forty-five , " ) self.assertEqual( enword("123456", -1), "one hundred and twenty-three thousand, four hundred and fifty-six , ", ) self.assertEqual( enword("1234567", -1), "one million, two hundred and thirty-four thousand, " "five hundred and sixty-seven , ", ) def test_numwords(self): p = inflect.engine() numwords = p.number_to_words for n, word in ( ("1", "one"), ("10", "ten"), ("100", "one hundred"), ("1000", "one thousand"), ("10000", "ten thousand"), ("100000", "one hundred thousand"), ("1000000", "one million"), ("10000000", "ten million"), ("+10", "plus ten"), ("-10", "minus ten"), ("10.", "ten point"), (".10", "point one zero"), ): self.assertEqual(numwords(n), word) for n, word, wrongword in ( # TODO: should be one point two three ("1.23", "one point two three", "one point twenty-three"), ): self.assertEqual(numwords(n), word) for n, txt in ( (3, "three bottles of beer on the wall"), (2, "two bottles of beer on the wall"), (1, "a solitary bottle of beer on the wall"), (0, "no more bottles of beer on the wall"), ): self.assertEqual( "{}{}".format( numwords(n, one="a solitary", zero="no more"), p.plural(" bottle of beer on the wall", n), ), txt, ) self.assertEqual(numwords(0, one="one", zero="zero"), "zero") self.assertEqual(numwords("1234"), "one thousand, two hundred and thirty-four") self.assertEqual( numwords("1234", wantlist=True), ["one thousand", "two hundred and thirty-four"], ) self.assertEqual( numwords("1234567", wantlist=True), [ "one million", "two hundred and thirty-four thousand", "five hundred and sixty-seven", ], ) self.assertEqual(numwords("+10", wantlist=True), ["plus", "ten"]) self.assertEqual( numwords("1234", andword=""), "one thousand, two hundred thirty-four" ) self.assertEqual( numwords("1234", andword="plus"), "one thousand, two hundred plus thirty-four", ) self.assertEqual(numwords(p.ordinal("21")), "twenty-first") self.assertEqual(numwords("9", threshold=10), "nine") self.assertEqual(numwords("10", threshold=10), "ten") self.assertEqual(numwords("11", threshold=10), "11") self.assertEqual(numwords("1000", threshold=10), "1,000") self.assertEqual(numwords("123", threshold=10), "123") self.assertEqual(numwords("1234", threshold=10), "1,234") self.assertEqual(numwords("1234.5678", threshold=10), "1,234.5678") self.assertEqual(numwords("1", decimal=None), "one") self.assertEqual( numwords("1234.5678", decimal=None), "twelve million, three hundred and forty-five " "thousand, six hundred and seventy-eight", ) def test_numwords_group(self): p = inflect.engine() numwords = p.number_to_words self.assertEqual(numwords("12345", group=2), "twelve, thirty-four, five") # TODO: 'hundred and' missing self.TODO( numwords("12345", group=3), "one hundred and twenty-three", "one twenty-three, forty-five", ) self.assertEqual( numwords("123456", group=3), "one twenty-three, four fifty-six" ) self.assertEqual(numwords("12345", group=1), "one, two, three, four, five") self.assertEqual( numwords("1234th", group=0, andword="and"), "one thousand, two hundred and thirty-fourth", ) self.assertEqual( numwords(p.ordinal("1234"), group=0), "one thousand, two hundred and thirty-fourth", ) self.assertEqual(numwords("120", group=2), "twelve, zero") self.assertEqual(numwords("120", group=2, zero="oh", one="unity"), "twelve, oh") # TODO: ignoring 'one' param with group=2 self.TODO( numwords("101", group=2, zero="oh", one="unity"), "ten, unity", "ten, one" ) self.assertEqual( numwords("555_1202", group=1, zero="oh"), "five, five, five, one, two, oh, two", ) self.assertEqual( numwords("555_1202", group=1, one="unity"), "five, five, five, unity, two, zero, two", ) self.assertEqual( numwords("123.456", group=1, decimal="mark", one="one"), "one, two, three, mark, four, five, six", ) inflect.STDOUT_ON = False self.assertRaises(BadChunkingOptionError, numwords, "1234", group=4) inflect.STDOUT_ON = True def test_wordlist(self): p = inflect.engine() wordlist = p.join self.assertEqual(wordlist([]), "") self.assertEqual(wordlist(("apple",)), "apple") self.assertEqual(wordlist(("apple", "banana")), "apple and banana") self.assertEqual( wordlist(("apple", "banana", "carrot")), "apple, banana, and carrot" ) self.assertEqual( wordlist(("apple", "1,000", "carrot")), "apple; 1,000; and carrot" ) self.assertEqual( wordlist(("apple", "1,000", "carrot"), sep=","), "apple, 1,000, and carrot" ) self.assertEqual( wordlist(("apple", "banana", "carrot"), final_sep=""), "apple, banana and carrot", ) self.assertEqual( wordlist(("apple", "banana", "carrot"), final_sep=";"), "apple, banana; and carrot", ) self.assertEqual( wordlist(("apple", "banana", "carrot"), conj="or"), "apple, banana, or carrot", ) self.assertEqual( wordlist(("apple", "banana"), conj=" or "), "apple or banana" ) self.assertEqual( wordlist(("apple", "banana"), conj="&"), "apple & banana" ) # TODO: want spaces here. Done, report upstream self.assertEqual( wordlist(("apple", "banana"), conj="&", conj_spaced=False), "apple&banana" ) self.assertEqual( wordlist(("apple", "banana"), conj="& ", conj_spaced=False), "apple& banana" ) self.assertEqual( wordlist(("apple", "banana", "carrot"), conj=" or "), "apple, banana, or carrot", ) self.assertEqual( wordlist(("apple", "banana", "carrot"), conj="+"), "apple, banana, + carrot" ) self.assertEqual( wordlist(("apple", "banana", "carrot"), conj="&"), "apple, banana, & carrot" ) # TODO: want space here. Done, report updtream self.assertEqual( wordlist(("apple", "banana", "carrot"), conj="&", conj_spaced=False), "apple, banana,&carrot", ) # TODO: want space here. Done, report updtream self.assertEqual( wordlist(("apple", "banana", "carrot"), conj=" &", conj_spaced=False), "apple, banana, &carrot", ) # TODO: want space here. Done, report updtream def test_print(self): inflect.STDOUT_ON = True inflect.print3("") # make sure it doesn't crash inflect.STDOUT_ON = False def test_doc_examples(self): p = inflect.engine() self.assertEqual(p.plural_noun("I"), "we") self.assertEqual(p.plural_verb("saw"), "saw") self.assertEqual(p.plural_adj("my"), "our") self.assertEqual(p.plural_noun("saw"), "saws") self.assertEqual(p.plural("was"), "were") self.assertEqual(p.plural("was", 1), "was") self.assertEqual(p.plural_verb("was", 2), "were") self.assertEqual(p.plural_verb("was"), "were") self.assertEqual(p.plural_verb("was", 1), "was") for errors, txt in ( (0, "There were no errors"), (1, "There was 1 error"), (2, "There were 2 errors"), ): self.assertEqual( "There {}{}".format( p.plural_verb("was", errors), p.no(" error", errors) ), txt, ) self.assertEqual( p.inflect( "There plural_verb('was',%d) no('error',%d)" % (errors, errors) ), txt, ) for num1, num2, txt in ((1, 2, "I saw 2 saws"), (2, 1, "we saw 1 saw")): self.assertEqual( "{}{}{} {}{}".format( p.num(num1, ""), p.plural("I"), p.plural_verb(" saw"), p.num(num2), p.plural_noun(" saw"), ), txt, ) self.assertEqual( p.inflect( "num(%d, False)plural('I') plural_verb('saw') " "num(%d) plural_noun('saw')" % (num1, num2) ), txt, ) self.assertEqual(p.a("a cat"), "a cat") for word, txt in ( ("cat", "a cat"), ("aardvark", "an aardvark"), ("ewe", "a ewe"), ("hour", "an hour"), ): self.assertEqual( p.a("{} {}".format(p.number_to_words(1, one="a"), word)), txt ) p.num(2) def test_deprecation(self): p = inflect.engine() for meth in ( "pl", "plnoun", "plverb", "pladj", "sinoun", "prespart", "numwords", "plequal", "plnounequal", "plverbequal", "pladjequal", "wordlist", ): self.assertRaises(DeprecationWarning, getattr, p, meth) def test_unknown_method(self): p = inflect.engine() with self.assertRaises(AttributeError): p.unknown_method # TODO: test .inflectrc file code if __name__ == "__main__": try: unittest.main() except SystemExit: pass inflect-2.1.0/tests/test_unicode.py0000644000076500000240000000102613372337710017726 0ustar jaracostaff00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest import inflect class TestUnicode(unittest.TestCase): """ Unicode compatibility test cases """ def test_unicode_plural(self): """ Unicode compatibility test cases for plural """ engine = inflect.engine() unicode_test_cases = {"cliché": "clichés", "ångström": "ångströms"} for singular, plural in unicode_test_cases.items(): self.assertEqual(plural, engine.plural(singular)) inflect-2.1.0/tests/words.txt0000644000076500000240000000001513274375005016563 0ustar jaracostaff00000000000000Times Jones inflect-2.1.0/tox.ini0000644000076500000240000000061613372337710015044 0ustar jaracostaff00000000000000[tox] envlist = python [tox:travis] pypy = pypy pypy3 = pypy3 2.7 = py27 3.4 = py34 3.5 = py35 3.6 = py36, black 3.7 = py37, flake8 [testenv] deps = pytest pytest-cov nose six commands = pytest --cov=inflect {posargs} [testenv:flake8] deps = flake8 commands = flake8 skip_install = true [testenv:black] deps = black commands = black --check --diff . skip_install = true