inflect-0.2.5/ 0000775 0001750 0001750 00000000000 12454040536 013053 5 ustar alex alex 0000000 0000000 inflect-0.2.5/inflect.egg-info/ 0000775 0001750 0001750 00000000000 12454040536 016171 5 ustar alex alex 0000000 0000000 inflect-0.2.5/inflect.egg-info/PKG-INFO 0000664 0001750 0001750 00000167567 12454040536 017314 0 ustar alex alex 0000000 0000000 Metadata-Version: 1.1
Name: inflect
Version: 0.2.5
Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words
Home-page: http://pypi.python.org/pypi/inflect
Author: Alex Gronholm
Author-email: alex.gronholm@nextday.fi
License: UNKNOWN
Description: ==========
inflect.py
==========
NAME
====
inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.
VERSION
=======
This document describes version 0.2.4 of inflect.py
INSTALLATION
============
``pip install -e git+https://github.com/pwdyson/inflect.py#egg=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.)
COPYRIGHT
=========
Copyright (C) 2010 Paul Dyson
Based upon the Perl module Lingua::EN::Inflect by Damian Conway.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
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.python.org/pypi/inflect
This module can be installed via ``easy_install inflect``
Repository available at http://github.com/pwdyson/inflect.py
Keywords: plural,inflect,participle
Platform: UNKNOWN
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Affero General Public License v3
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Linguistic
Provides: inflect
inflect-0.2.5/inflect.egg-info/SOURCES.txt 0000664 0001750 0001750 00000001036 12454040536 020055 0 ustar alex alex 0000000 0000000 CHANGES.txt
COPYING.txt
MANIFEST.in
README.rst
inflect.py
setup.cfg
setup.py
inflect.egg-info/PKG-INFO
inflect.egg-info/SOURCES.txt
inflect.egg-info/dependency_links.txt
inflect.egg-info/top_level.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/words.txt inflect-0.2.5/inflect.egg-info/dependency_links.txt 0000664 0001750 0001750 00000000001 12454040536 022237 0 ustar alex alex 0000000 0000000
inflect-0.2.5/inflect.egg-info/top_level.txt 0000664 0001750 0001750 00000000010 12454040536 020712 0 ustar alex alex 0000000 0000000 inflect
inflect-0.2.5/tests/ 0000775 0001750 0001750 00000000000 12454040536 014215 5 ustar alex alex 0000000 0000000 inflect-0.2.5/tests/test_an.py 0000664 0001750 0001750 00000001613 12155017015 016217 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_classical_all.py 0000664 0001750 0001750 00000005570 12155020507 020415 0 ustar alex alex 0000000 0000000 import 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-0.2.5/tests/test_classical_ancient.py 0000664 0001750 0001750 00000001477 12155020617 021272 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_classical_herd.py 0000664 0001750 0001750 00000001503 12155020600 020551 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_classical_names.py 0000664 0001750 0001750 00000001707 12155020434 020745 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_classical_person.py 0000664 0001750 0001750 00000001617 12155020454 021152 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_classical_zero.py 0000664 0001750 0001750 00000001446 12155020073 020620 0 ustar alex alex 0000000 0000000 from 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-0.2.5/tests/test_compounds.py 0000664 0001750 0001750 00000001075 12157672666 017657 0 ustar alex alex 0000000 0000000 from nose.tools import eq_
import inflect
class TestCompounds(object):
def setup(self):
self.p = inflect.engine()
def test_compound_1(self):
eq_(self.p.singular_noun('hello-out-there'), 'hello-out-there')
def test_compound_2(self):
eq_(self.p.singular_noun('hello out there'), 'hello out there')
def test_compound_3(self):
eq_(self.p.singular_noun('continue-to-operate'), 'continue-to-operate')
def test_compound_4(self):
eq_(self.p.singular_noun('case of diapers'), 'case of diapers')
inflect-0.2.5/tests/test_inflections.py 0000664 0001750 0001750 00000122654 12155022001 020136 0 ustar alex alex 0000000 0000000
from nose.tools import eq_, assert_not_equal
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
yield 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(%s,%s) == %s != %s' % (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(%s,%s) == %s != %s' % (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(%s) == %s != %s" % (mod_plural, p.singular_noun(mod_plural, 1), singular))
eq_(p.singular_noun(class_plural, 1), singular,
msg="p.singular_noun(%s) == %s != %s" % (class_plural, p.singular_noun(class_plural, 1), singular))
'''
don't see any test data for this ???
elsif (/^\s+(an?)\s+(.*?)\s*$/)
{
$article = $1
$word = $2
$Aword = A($word)
ok ("$article $word" eq $Aword, "$article $word")
}
'''
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 get_data():
return '''
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
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
'''.split('\n')
inflect-0.2.5/tests/test_join.py 0000664 0001750 0001750 00000006126 12155016673 016575 0 ustar alex alex 0000000 0000000
from 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='-->%s != %s<-- 3 words, different final sep, no conjunction' %
(p.join(words, final_sep='...', conj=''), "apple, banana... carrot"))
eq_(p.join(words, conj='or'),
"apple, banana, or carrot", msg='%s != %s 3 words, different conjunction' % (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='%s != %s<-- comma-inclusive 3 words' % (p.join(words), "apple,fuji, banana; and carrot"))
eq_(p.join(words, final_sep=''),
"apple,fuji; banana and carrot", msg='join(%s) == "%s" != "%s"' % (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(%s, final_sep='...', conj='') == %s != %s" % (
words, p.join(words, final_sep='...', conj=''), 'apple carrot'))
eq_(p.join(words, final_sep='...', conj='', conj_spaced=False),
"applecarrot", msg="join(%s, final_sep='...', conj='') == %s != %s" % (
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-0.2.5/tests/test_numwords.py 0000664 0001750 0001750 00000041743 12155020721 017505 0 ustar alex alex 0000000 0000000
from 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 %s (<= %s)" % (n, thresh))
else:
# $threshed =~ s/\D//gxms;
eq_(threshed, str(n), msg="p.number_to_words(%s, thresold=%s) == %s != %s" % (
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:
yield go, p, i
def go(p, i):
eq_(p.number_to_words(i[0]), i[1], msg="number_to_words(%s) == %s != %s" % (
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(%s)) == %s != %s" % (
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-0.2.5/tests/test_pl_si.py 0000664 0001750 0001750 00000002305 12155015644 016734 0 ustar alex alex 0000000 0000000
# 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)
yield check_pl_si, p, word
p.classical(all=True)
yield 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('%s %s %s\n' % (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-0.2.5/tests/test_pwd.py 0000664 0001750 0001750 00000126047 12155015412 016423 0 ustar alex alex 0000000 0000000 #!/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!: %s == %s' % (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)", "1"),
("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("%s") != "%s"' % (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"),
# TODO: extra space when space before number. Is this desirable?
("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("%s") != "%s"' % (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'),
):
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_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='%s("%s") == "%s" != "%s"' % (
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'),
):
self.assertEqual(p.singular_noun(plur), sing)
self.assertEqual(p.inflect('singular_noun(%s)' % plur), sing)
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(%s) == %s != %s" % (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(%s) == %s != %s" % (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(%s) == %s != %s" % (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(%s) == %s != %s" % (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)
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("%s") == %s != "%s"' % (
sing, p._plnoun(sing), plur))
self.assertEqual(p._sinoun(plur), sing,
msg='p._sinoun("%s") != "%s"' % (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("%s") != "%s"' % (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')
self.assertEqual(p._pl_special_verb('zzzoes'), 'zzzo') # TODO: what's a real word to test this case?
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)
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("%s%s" % (
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 %s%s" % (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("%s%s%s %s%s" % (
p.num(num1, ""),
p.plural("I"),
p.plural_verb(" saw"),
p.num(num2),
p.plural_noun(" saw")),
txt)
self.assertEqual(
p.inflect(
'num(%d,)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('%s %s' % (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)
# TODO: test .inflectrc file code
if __name__ == "__main__":
try:
unittest.main()
except SystemExit:
pass
inflect-0.2.5/tests/words.txt 0000644 0001750 0001750 00000000015 12150047530 016100 0 ustar alex alex 0000000 0000000 Times
Jones
inflect-0.2.5/CHANGES.txt 0000664 0001750 0001750 00000003651 12357031736 014675 0 ustar alex alex 0000000 0000000 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-0.2.5/COPYING.txt 0000644 0001750 0001750 00000103330 12150047530 014714 0 ustar alex alex 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
inflect-0.2.5/MANIFEST.in 0000644 0001750 0001750 00000000152 12155021413 014574 0 ustar alex alex 0000000 0000000 include COPYING.txt
include CHANGES.txt
include README.rst
include tests/test*.py
include tests/words.txt
inflect-0.2.5/README.rst 0000664 0001750 0001750 00000140272 12357031736 014554 0 ustar alex alex 0000000 0000000 ==========
inflect.py
==========
NAME
====
inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.
VERSION
=======
This document describes version 0.2.4 of inflect.py
INSTALLATION
============
``pip install -e git+https://github.com/pwdyson/inflect.py#egg=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.)
COPYRIGHT
=========
Copyright (C) 2010 Paul Dyson
Based upon the Perl module Lingua::EN::Inflect by Damian Conway.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
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.python.org/pypi/inflect
This module can be installed via ``easy_install inflect``
Repository available at http://github.com/pwdyson/inflect.py
inflect-0.2.5/inflect.py 0000664 0001750 0001750 00000304603 12454032346 015057 0 ustar alex alex 0000000 0000000 '''
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.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
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.python.org/pypi/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 re import match, search, subn, IGNORECASE, VERBOSE
from re import split as splitre
from re import error as reerror
from re import sub as resub
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
__ver_major__ = 0
__ver_minor__ = 2
__ver_patch__ = 5
__ver_sub__ = ""
__version__ = "%d.%d.%d%s" % (__ver_major__, __ver_minor__,
__ver_patch__, __ver_sub__)
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 = dict([(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 = dict([(v, k) for (k, v) in pl_sb_irregular_caps.items()])
si_sb_irregular_compound = dict([(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 = set((
"ado", "ISO", "NATO", "NCO", "NGO", "oto",
))
si_sb_U_o_os_complete = set('%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': ['(?!major|lieutenant|brigadier|adjutant|.*star)\S+'],
'martial': ['court'],
}
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 = set(['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'] = dict([(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'] = dict([(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 = dict((k, True) for k in list(def_classical.keys()))
no_classical = dict((k, False) for k in list(def_classical.keys()))
# TODO: .inflectrc file does not work
# can't just execute methods from another file like this
# for rcfile in (pathjoin(dirname(__file__), '.inflectrc'),
# expanduser(pathjoin(('~'), '.inflectrc'))):
# if isfile(rcfile):
# try:
# execfile(rcfile)
# except:
# print3("\nBad .inflectrc file (%s):\n" % rcfile)
# raise BadRcFileError
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('%s() deprecated, use %s()' % (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:
match(pattern, '')
except reerror:
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
# can't find a pattern that doesn't pass the following test:
# if pattern is None:
# return
# try:
# resub('', pattern, '')
# except reerror:
# print3("\nBad user-defined plural pattern:\n\t%s\n" % pattern)
# raise BadUserDefinedPatternError
def ud_match(self, word, wordlist):
for i in range(len(wordlist) - 2, -2, -2): # backwards through even elements
mo = search(r'^%s$' % wordlist[i], word, IGNORECASE)
if mo:
if wordlist[i + 1] is None:
return None
pl = resub(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 nummo(self, matchobject):
'''
num but take a matchobject
use groups 1 and 2 in matchobject
'''
return self.num(matchobject.group(1), matchobject.group(2))
def plmo(self, matchobject):
'''
plural but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.plural(matchobject.group(1), matchobject.group(3))
def plnounmo(self, matchobject):
'''
plural_noun but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.plural_noun(matchobject.group(1), matchobject.group(3))
def plverbmo(self, matchobject):
'''
plural_verb but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.plural_verb(matchobject.group(1), matchobject.group(3))
def pladjmo(self, matchobject):
'''
plural_adj but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.plural_adj(matchobject.group(1), matchobject.group(3))
def sinounmo(self, matchobject):
'''
singular_noun but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.singular_noun(matchobject.group(1), matchobject.group(3))
def amo(self, matchobject):
'''
A but take a matchobject
use groups 1 and 3 in matchobject
'''
if matchobject.group(3) is None:
return self.a(matchobject.group(1))
return self.a(matchobject.group(1), matchobject.group(3))
def nomo(self, matchobject):
'''
NO but take a matchobject
use groups 1 and 3 in matchobject
'''
return self.no(matchobject.group(1), matchobject.group(3))
def ordinalmo(self, matchobject):
'''
ordinal but take a matchobject
use group 1
'''
return self.ordinal(matchobject.group(1))
def numwordsmo(self, matchobject):
'''
number_to_words but take a matchobject
use group 1
'''
return self.number_to_words(matchobject.group(1))
def prespartmo(self, matchobject):
'''
prespart but take a matchobject
use group 1
'''
return self.present_participle(matchobject.group(1))
# 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
sections = splitre(r"(num\([^)]*\))", text)
inflection = []
for section in sections:
(section, count) = subn(r"num\(\s*?(?:([^),]*)(?:,([^)]*))?)?\)", self.nummo, section)
if not count:
total = -1
while total:
(section, total) = subn(
r"(?x)\bplural \( ([^),]*) (, ([^)]*) )? \) ",
self.plmo, section)
(section, count) = subn(
r"(?x)\bplural_noun \( ([^),]*) (, ([^)]*) )? \) ",
self.plnounmo, section)
total += count
(section, count) = subn(
r"(?x)\bplural_verb \( ([^),]*) (, ([^)]*) )? \) ",
self.plverbmo, section)
total += count
(section, count) = subn(
r"(?x)\bplural_adj \( ([^),]*) (, ([^)]*) )? \) ",
self.pladjmo, section)
total += count
(section, count) = subn(
r"(?x)\bsingular_noun \( ([^),]*) (, ([^)]*) )? \) ",
self.sinounmo, section)
total += count
(section, count) = subn(
r"(?x)\ban? \( ([^),]*) (, ([^)]*) )? \) ",
self.amo, section)
total += count
(section, count) = subn(
r"(?x)\bno \( ([^),]*) (, ([^)]*) )? \) ",
self.nomo, section)
total += count
(section, count) = subn(
r"(?x)\bordinal \( ([^)]*) \) ",
self.ordinalmo, section)
total += count
(section, count) = subn(
r"(?x)\bnumber_to_words \( ([^)]*) \) ",
self.numwordsmo, section)
total += count
(section, count) = subn(
r"(?x)\bpresent_participle \( ([^)]*) \) ",
self.prespartmo, section)
total += count
inflection.append(section)
self.persistent_count = save_persistent_count
return "".join(inflection)
# ## PLURAL SUBROUTINES
def postprocess(self, orig, inflected):
"""
FIX PEDANTRY AND CAPITALIZATION :-)
"""
if '|' in inflected:
inflected = inflected.split('|')[self.classical_dict['all']]
if orig == "I":
return inflected
if orig == orig.upper():
return inflected.upper()
if orig[0] == orig[0].upper():
return '%s%s' % (inflected[0].upper(),
inflected[1:])
return inflected
def partition_word(self, text):
mo = search(r'\A(\s*)(.+?)(\s*)\Z', text)
try:
return mo.group(1), mo.group(2), mo.group(3)
except AttributeError: # empty string
return '', '', ''
# def pl(self, *args, **kwds):
# print 'pl() deprecated, use plural()'
# raise DeprecationWarning
# return self.plural(*args, **kwds)
#
# def plnoun(self, *args, **kwds):
# print 'plnoun() deprecated, use plural_noun()'
# raise DeprecationWarning
# return self.plural_noun(*args, **kwds)
#
# def plverb(self, *args, **kwds):
# print 'plverb() deprecated, use plural_verb()'
# raise DeprecationWarning
# return self.plural_verb(*args, **kwds)
#
# def pladj(self, *args, **kwds):
# print 'pladj() deprecated, use plural_adj()'
# raise DeprecationWarning
# return self.plural_adj(*args, **kwds)
#
# def sinoun(self, *args, **kwds):
# print 'sinoun() deprecated, use singular_noun()'
# raise DeprecationWarning
# return self.singular_noun(*args, **kwds)
#
# def prespart(self, *args, **kwds):
# print 'prespart() deprecated, use present_participle()'
# raise DeprecationWarning
# return self.present_participle(*args, **kwds)
#
# def numwords(self, *args, **kwds):
# print 'numwords() deprecated, use number_to_words()'
# raise DeprecationWarning
# return self.number_to_words(*args, **kwds)
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 "%s%s%s" % (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 "%s%s%s" % (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 "%s%s%s" % (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 "%s%s%s" % (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 "%s%s%s" % (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):
if search(r"(%s)(%s\|\1%s|%s\|\1%s)" % (stems, end1, end2, end2, end1), pair):
return True
return False
def _pl_check_plurals_N(self, word1, word2):
pair = "%s|%s" % (word1, word2)
if pair in list(pl_sb_irregular_s.values()):
return True
if pair in list(pl_sb_irregular.values()):
return True
if pair in list(pl_sb_irregular_caps.values()):
return True
for (stems, end1, end2) in (
(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")
):
if self._pl_reg_plurals(pair, stems, end1, end2):
return True
return False
def _pl_check_plurals_adj(self, word1, word2):
# VERSION: tuple in endswith requires python 2.5
word1a = word1[:word1.rfind("'")] if word1.endswith(("'s", "'")) else ''
word2a = word2[:word2.rfind("'")] if word2.endswith(("'s", "'")) else ''
# TODO: BUG? report upstream. I don't think you should chop off the s'
# word1b = word1[:-2] if word1.endswith("s'") else ''
# word2b = word2[:-2] if word2.endswith("s'") else ''
# TODO: dresses', dresses's -> dresses, dresses when chop off letters
# then they return False because they are the same. Need to fix this.
if word1a:
if word2a and (self._pl_check_plurals_N(word1a, word2a)
or self._pl_check_plurals_N(word2a, word1a)):
return True
# if word2b and ( self._pl_check_plurals_N(word1a, word2b)
# or self._pl_check_plurals_N(word2b, word1a) ):
# return True
# if word1b:
# if word2a and ( self._pl_check_plurals_N(word1b, word2a)
# or self._pl_check_plurals_N(word2a, word1b) ):
# return True
# if word2b and ( self._pl_check_plurals_N(word1b, word2b)
# or self._pl_check_plurals_N(word2b, word1b) ):
# return True
return False
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 = search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, IGNORECASE)
if mo and mo.group(2) != '':
return "%s%s" % (self._plnoun(mo.group(1), 2), mo.group(2))
if ' a ' in lowerword or '-a-' in lowerword:
mo = search(r"^(?:%s)$" % pl_sb_prep_dual_compound, word, IGNORECASE)
if mo and mo.group(2) != '' and mo.group(3) != '':
return "%s%s%s" % (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:])
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 '%s%s' % (word[:-llen],
pl_sb_irregular_caps[wordlast])
if lowerwordlast in list(pl_sb_irregular.keys()):
llen = len(lowerwordlast)
return '%s%s' % (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 '%s%s' % (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 == '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'
# Wouldn't special words
# ending with 's' always have been caught, regardless of them starting
# with a capital letter (i.e. being names)
# It makes sense below to do this for words ending in 'y' so that
# Sally -> Sallys. But not sure it makes sense here. Where is the case
# of a word ending in s that is caught here and would otherwise have been
# caught below?
#
# removing it as I can't find a case that executes it
# TODO: check this again
#
# if (self.classical_dict['names']):
# mo = search(r"([A-Z].*s)$", word)
# if mo:
# return "%ses" % mo.group(1)
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'
# ## (r"(.*)(us)$", "%s%ses"), TODO: why is this commented?
# 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 "%s%s" % (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 "%sn't%s" % (plverb_irregular_pres[firstword[:-3]], word[len(firstword):])
if firstword.endswith("n't"):
return word
# HANDLE SPECIAL CASES
mo = search(r"^(%s)$" % plverb_special_s, word)
if mo:
return False
if 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]
# # mo = search(r"^(.*)([cs]h|[x]|zz|ss)es$",
# # word, IGNORECASE)
# # if mo:
# # return "%s%s" % (mo.group(1), mo.group(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 = search(r"^(.*[^s])s$", word, 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 = search(r"^(%s)((\s.*)?)$" % plverb_ambiguous_pres_keys, word, IGNORECASE)
if mo:
return "%s%s" % (plverb_ambiguous_pres[mo.group(1).lower()], mo.group(2))
# HANDLE AMBIGUOUS PRETERITE AND PERFECT TENSES
mo = search(r"^(%s)((\s.*)?)$" % plverb_ambiguous_non_pres, word, 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 = search(r"^(%s)$" % pl_adj_special_keys,
word, IGNORECASE)
if mo:
return "%s" % (pl_adj_special[mo.group(1).lower()])
# HANDLE POSSESSIVES
mo = search(r"^(%s)$" % pl_adj_poss_keys,
word, IGNORECASE)
if mo:
return "%s" % (pl_adj_poss[mo.group(1).lower()])
mo = search(r"^(.*)'s?$",
word)
if mo:
pl = self.plural_noun(mo.group(1))
trailing_s = "" if pl[-1] == 's' else "s"
return "%s'%s" % (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
# HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.)
mo = search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, IGNORECASE)
if mo and mo.group(2) != '':
return "%s%s" % (self._sinoun(mo.group(1), 1, gender=gender), mo.group(2))
# how to reverse this one?
# mo = search(r"^(?:%s)$" % pl_sb_prep_dual_compound, word, IGNORECASE)
# if mo and mo.group(2) != '' and mo.group(3) != '':
# return "%s%s%s" % (self._sinoun(mo.group(1), 1),
# mo.group(2),
# self._sinoun(mo.group(3), 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._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 '%s%s' % (word[:-llen],
si_sb_irregular_caps[wordlast])
if lowerwordlast in list(si_sb_irregular.keys()):
llen = len(lowerwordlast)
return '%s%s' % (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 '%s%s' % (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]
# Wouldn't special words
# ending with 's' always have been caught, regardless of them starting
# with a capital letter (i.e. being names)
# It makes sense below to do this for words ending in 'y' so that
# Sally -> Sallys. But not sure it makes sense here. Where is the case
# of a word ending in s that is caught here and would otherwise have been
# caught below?
#
# removing it as I can't find a case that executes it
# TODO: check this again
#
# if (self.classical_dict['names']):
# mo = search(r"([A-Z].*ses)$", word)
# if mo:
# return "%s" % mo.group(1)
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]
# (r"(.*)(us)es$", "%s%s"), TODO: why is this commented?
# 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 = search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z",
text, 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 "%s%s%s" % (pre, result, post)
return ''
an = a
def _indef_article(self, word, count):
mycount = self.get_count(count)
if mycount != 1:
return "%s %s" % (count, word)
# HANDLE USER-DEFINED VARIANTS
value = self.ud_match(word, self.A_a_user_defined)
if value is not None:
return "%s %s" % (value, word)
# HANDLE ORDINAL FORMS
for a in (
(r"^(%s)" % A_ordinal_a, "a"),
(r"^(%s)" % A_ordinal_an, "an"),
):
mo = search(a[0], word, IGNORECASE)
if mo:
return "%s %s" % (a[1], word)
# HANDLE SPECIAL CASES
for a in (
(r"^(%s)" % A_explicit_an, "an"),
(r"^[aefhilmnorsx]$", "an"),
(r"^[bcdgjkpqtuvwyz]$", "a"),
):
mo = search(a[0], word, IGNORECASE)
if mo:
return "%s %s" % (a[1], word)
# HANDLE ABBREVIATIONS
for a in (
(r"(%s)" % A_abbrev, "an", VERBOSE),
(r"^[aefhilmnorsx][.-]", "an", IGNORECASE),
(r"^[a-z][.-]", "a", IGNORECASE),
):
mo = search(a[0], word, a[2])
if mo:
return "%s %s" % (a[1], word)
# HANDLE CONSONANTS
mo = search(r"^[^aeiouy]", word, 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 = search(a[0], word, IGNORECASE)
if mo:
return "%s %s" % (a[1], word)
# HANDLE SPECIAL CAPITALS
mo = search(r"^U[NK][AIEO]?", word)
if mo:
return "a %s" % word
# HANDLE VOWELS
mo = search(r"^[aeiou]", word, IGNORECASE)
if mo:
return "an %s" % word
# HANDLE y... (BEFORE CERTAIN CONSONANTS IMPLIES (UNNATURALIZED) "i.." SOUND)
mo = search(r"^(%s)" % A_y_cons, word, 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 = 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 "%sno %s%s" % (pre, self.plural(word, 0), post)
else:
return "%s%s %s%s" % (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]))$", "\g<1>\g<2>"),
):
(ans, num) = 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 match(r"\d", str(num)):
try:
num % 2
n = num
except TypeError:
if '.' in str(num):
try:
n = int(num[-1]) # numbers after decimal, so only need last one for ordinal
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 "%s%s" % (num, post)
else:
mo = search(r"(%s)\Z" % ordinal_suff, num)
try:
post = ordinal[mo.group(1)]
return resub(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 "%s%s" % (unit[units], self.millfn(mindex))
def tenfn(self, tens, units, mindex=0):
if tens != 1:
return "%s%s%s%s" % (ten[tens],
'-' if tens and units else '',
unit[units],
self.millfn(mindex))
return "%s%s" % (teen[units], mill[mindex])
def hundfn(self, hundreds, tens, units, mindex):
if hundreds:
return "%s hundred%s%s%s, " % (unit[hundreds], # use unit not unitfn as simpler
" %s " % self.number_args['andword'] if tens or units else '',
self.tenfn(tens, units),
self.millfn(mindex))
if tens or units:
return "%s%s, " % (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:
# TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl
return "%s, " % unit[units]
else:
return " %s, " % self.number_args['zero']
def group1bsub(self, mo):
units = int(mo.group(1))
if units:
# TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl
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 " %s %s, " % (self.number_args['zero'], unit[units])
return " %s %s, " % (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]
# TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl
else:
hunword = " %s" % self.number_args['zero']
if tens:
tenword = self.tenfn(tens, units)
elif units:
tenword = " %s %s" % (self.number_args['zero'], unit[units])
else:
tenword = " %s %s" % (self.number_args['zero'], self.number_args['zero'])
return "%s %s, " % (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 = resub(r"(\d)", self.group1sub, num)
elif group == 2:
num = resub(r"(\d)(\d)", self.group2sub, num)
num = resub(r"(\d)", self.group1bsub, num, 1)
# group1bsub same as
# group1sub except it doesn't use the default word for one.
# Is this required? i.e. is the default word not to beused when
# grouping in pairs?
#
# No. This is a bug. Fixed. TODO: report upstream.
elif group == 3:
num = resub(r"(\d)(\d)(\d)", self.group3sub, num)
num = resub(r"(\d)(\d)", self.group2sub, num, 1)
num = resub(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 = search(r"(\d)(\d)(\d)(?=\D*\Z)", num)
while mo:
num = resub(r"(\d)(\d)(\d)(?=\D*\Z)", self.hundsub, num, 1)
mo = search(r"(\d)(\d)(\d)(?=\D*\Z)", num)
num = resub(r"(\d)(\d)(?=\D*\Z)", self.tensub, num, 1)
num = resub(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 resub
rather than this fn
'''
return ''
def commafn(self, mo):
''' do a global ',' replace
TODO: surely this can be done with an option to resub
rather than this fn
'''
return ','
def spacefn(self, mo):
''' do a global ' ' replace
TODO: surely this can be done with an option to resub
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) = subn(r"(\d)(\d{3}(?:,|\Z))", r"\1,\2", spnum[0])
if n == 0:
break
try:
return "%s.%s" % (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 = resub(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 = resub(r"\s+,", self.commafn, chunk)
if group == 0 and first:
chunk = resub(r", (\S+)\s+\Z", " %s \\1" % andword, chunk)
chunk = resub(r"\s+", self.spacefn, chunk)
# chunk = resub(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 = search(r"(%s)\Z" % ordinal_suff, numchunks[-1])
if mo:
numchunks[-1] = resub(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 "%s%s" % (signout, ", ".join(numchunks))
else:
signout = "%s " % sign if sign else ''
num = "%s%s" % (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 += "%s %s" % (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 "%s%s%s" % (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 = "%s%s" % (final_sep, conj)
if sep_spaced:
sep += ' '
return "%s%s%s" % (sep.join(words[0:-1]), final_sep, words[-1])
inflect-0.2.5/setup.py 0000664 0001750 0001750 00000002643 12454026010 014561 0 ustar alex alex 0000000 0000000 import os
import inflect
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path, 'rb').read().decode('utf-8')
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='pwdyson@yahoo.com',
maintainer='Alex Gronholm',
maintainer_email='alex.gronholm@nextday.fi',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
inflect-0.2.5/PKG-INFO 0000664 0001750 0001750 00000167567 12454040536 014176 0 ustar alex alex 0000000 0000000 Metadata-Version: 1.1
Name: inflect
Version: 0.2.5
Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words
Home-page: http://pypi.python.org/pypi/inflect
Author: Alex Gronholm
Author-email: alex.gronholm@nextday.fi
License: UNKNOWN
Description: ==========
inflect.py
==========
NAME
====
inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.
VERSION
=======
This document describes version 0.2.4 of inflect.py
INSTALLATION
============
``pip install -e git+https://github.com/pwdyson/inflect.py#egg=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.)
COPYRIGHT
=========
Copyright (C) 2010 Paul Dyson
Based upon the Perl module Lingua::EN::Inflect by Damian Conway.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
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.python.org/pypi/inflect
This module can be installed via ``easy_install inflect``
Repository available at http://github.com/pwdyson/inflect.py
Keywords: plural,inflect,participle
Platform: UNKNOWN
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Affero General Public License v3
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Linguistic
Provides: inflect
inflect-0.2.5/setup.cfg 0000664 0001750 0001750 00000000130 12454040536 014666 0 ustar alex alex 0000000 0000000 [bdist_wheel]
universal = 1
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0