Patterns and Constructions#

from nltk.chunk.regexp import tag_pattern2re_pattern
from nltk.chunk import RegexpParser
from nltk.corpus import brown
import nltk
tag_pattern2re_pattern('<DT>?<NN.*>+')
'(<(DT)>)?(<(NN[^\\{\\}<>]*)>)+'
chunker = RegexpParser('''
NP:
    {<DT><NN.*><.*>*<NN.*>}
    }<VB.*>{
''')

#sent = brown.tagged_sents()[10]
#chunker.parse(sent)

sent = 'The article looks like a work written by a foreigner.'
sent = nltk.pos_tag(nltk.word_tokenize(sent))
sent_ct = chunker.parse(sent)
print(sent_ct)
(S
  (NP The/DT article/NN)
  looks/VBZ
  (NP like/IN a/DT work/NN)
  written/VBN
  (NP by/IN a/DT foreigner/NN)
  ./.)
sent_ct.productions()
#sent_ct.chomsky_normal_form()
sent_ct
sent_ct[0]
The Ghostscript executable isn't found.
See http://web.mit.edu/ghostscript/www/Install.htm
If you're using a Mac, you can try installing
https://docs.brew.sh/Installation then `brew install ghostscript`
---------------------------------------------------------------------------
LookupError                               Traceback (most recent call last)
~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/nltk/tree.py in _repr_png_(self)
    805                             env_vars=['PATH'],
--> 806                             verbose=False,
    807                         )

~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/nltk/internals.py in find_binary(name, path_to_bin, env_vars, searchpath, binary_names, url, verbose)
    696         find_binary_iter(
--> 697             name, path_to_bin, env_vars, searchpath, binary_names, url, verbose
    698         )

~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/nltk/internals.py in find_binary_iter(name, path_to_bin, env_vars, searchpath, binary_names, url, verbose)
    680     for file in find_file_iter(
--> 681         path_to_bin or name, env_vars, searchpath, binary_names, url, verbose
    682     ):

~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/nltk/internals.py in find_file_iter(filename, env_vars, searchpath, file_names, url, verbose, finding_dir)
    638         div = '=' * 75
--> 639         raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))
    640 

LookupError: 

===========================================================================
NLTK was unable to find the gs file!
Use software specific configuration paramaters or set the PATH environment variable.
===========================================================================

During handling of the above exception, another exception occurred:

LookupError                               Traceback (most recent call last)
~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

~/opt/anaconda3/envs/python-notes/lib/python3.7/site-packages/nltk/tree.py in _repr_png_(self)
    817                                         "https://docs.brew.sh/Installation then `brew install ghostscript`")                
    818                 print(pre_error_message, file=sys.stderr)
--> 819                 raise LookupError
    820 
    821             with open(out_path, 'rb') as sr:

LookupError: 
Tree('NP', [('The', 'DT'), ('article', 'NN')])
print(type(sent_ct[0].label))
print(sent_ct[0])
print(type(sent_ct[0].leaves))
print(type(sent_ct[1]))
type(sent_ct[2])
<class 'method'>
(NP The/DT article/NN)
<class 'method'>
<class 'tuple'>
nltk.tree.Tree
i=0
for subtree in sent_ct.subtrees():
    i=i+1
    print(str(i))
    print('label: {}'.format(subtree.label()))
    print(subtree)
1
label: S
(S
  (NP The/DT article/NN)
  looks/VBZ
  (NP like/IN a/DT work/NN)
  written/VBN
  (NP by/IN a/DT foreigner/NN)
  ./.)
2
label: NP
(NP The/DT article/NN)
3
label: NP
(NP like/IN a/DT work/NN)
4
label: NP
(NP by/IN a/DT foreigner/NN)
str(sent_ct)
'(S\n  (NP The/DT article/NN)\n  looks/VBZ\n  (NP like/IN a/DT work/NN)\n  written/VBN\n  (NP by/IN a/DT foreigner/NN)\n  ./.)'
for subtree in sent_ct.subtrees(filter=lambda t: t.label().endswith("NP")):
    print(subtree)
(NP The/DT article/NN)
(NP like/IN a/DT work/NN)
(NP by/IN a/DT foreigner/NN)
# write chunk rules
pat_chunker = RegexpParser('''
ADJ_AND_ADJ:
    {<JJ.*><CC><JJ.*>}
''')

for sent in brown.tagged_sents()[:500]:
    cur_t = pat_chunker.parse(sent)
    cur_pat = [pat for pat in cur_t.subtrees(filter=lambda t: t.label().startswith("ADJ_AND"))]
    if len(cur_pat)>0:
        print(cur_pat)
    
[Tree('ADJ_AND_ADJ', [('outmoded', 'JJ'), ('or', 'CC'), ('inadequate', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('fair', 'JJ'), ('and', 'CC'), ('equitable', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('rural', 'JJ'), ('and', 'CC'), ('urban', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('junior', 'JJ'), ('or', 'CC'), ('senior', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('medical', 'JJ'), ('and', 'CC'), ('dental', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('ambitious', 'JJ'), ('and', 'CC'), ('costly', 'JJ')]), Tree('ADJ_AND_ADJ', [('medical', 'JJ'), ('and', 'CC'), ('dental', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('medical', 'JJ'), ('and', 'CC'), ('dental', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('medical', 'JJ'), ('and', 'CC'), ('dental', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('tentative', 'JJ'), ('and', 'CC'), ('exploratory', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('military', 'JJ'), ('and', 'CC'), ('economic', 'JJ')])]
[Tree('ADJ_AND_ADJ', [('firmer', 'JJR'), ('and', 'CC'), ('tougher', 'JJR')])]
[Tree('ADJ_AND_ADJ', [('amateurish', 'JJ'), ('and', 'CC'), ('monumental', 'JJ')])]
nltk.help.upenn_tagset()
$: dollar
    $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$
'': closing quotation mark
    ' ''
(: opening parenthesis
    ( [ {
): closing parenthesis
    ) ] }
,: comma
    ,
--: dash
    --
.: sentence terminator
    . ! ?
:: colon or ellipsis
    : ; ...
CC: conjunction, coordinating
    & 'n and both but either et for less minus neither nor or plus so
    therefore times v. versus vs. whether yet
CD: numeral, cardinal
    mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
    seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
    fifteen 271,124 dozen quintillion DM2,000 ...
DT: determiner
    all an another any both del each either every half la many much nary
    neither no some such that the them these this those
EX: existential there
    there
FW: foreign word
    gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous
    lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte
    terram fiche oui corporis ...
IN: preposition or conjunction, subordinating
    astride among uppon whether out inside pro despite on by throughout
    below within for towards near behind atop around if like until below
    next into if beside ...
JJ: adjective or numeral, ordinal
    third ill-mannered pre-war regrettable oiled calamitous first separable
    ectoplasmic battery-powered participatory fourth still-to-be-named
    multilingual multi-disciplinary ...
JJR: adjective, comparative
    bleaker braver breezier briefer brighter brisker broader bumper busier
    calmer cheaper choosier cleaner clearer closer colder commoner costlier
    cozier creamier crunchier cuter ...
JJS: adjective, superlative
    calmest cheapest choicest classiest cleanest clearest closest commonest
    corniest costliest crassest creepiest crudest cutest darkest deadliest
    dearest deepest densest dinkiest ...
LS: list item marker
    A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
    SP-44007 Second Third Three Two * a b c d first five four one six three
    two
MD: modal auxiliary
    can cannot could couldn't dare may might must need ought shall should
    shouldn't will would
NN: noun, common, singular or mass
    common-carrier cabbage knuckle-duster Casino afghan shed thermostat
    investment slide humour falloff slick wind hyena override subhumanity
    machinist ...
NNP: noun, proper, singular
    Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
    Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
    Shannon A.K.C. Meltex Liverpool ...
NNPS: noun, proper, plural
    Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists
    Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques
    Apache Apaches Apocrypha ...
NNS: noun, common, plural
    undergraduates scotches bric-a-brac products bodyguards facets coasts
    divestitures storehouses designs clubs fragrances averages
    subjectivists apprehensions muses factory-jobs ...
PDT: pre-determiner
    all both half many quite such sure this
POS: genitive marker
    ' 's
PRP: pronoun, personal
    hers herself him himself hisself it itself me myself one oneself ours
    ourselves ownself self she thee theirs them themselves they thou thy us
PRP$: pronoun, possessive
    her his mine my our ours their thy your
RB: adverb
    occasionally unabatingly maddeningly adventurously professedly
    stirringly prominently technologically magisterially predominately
    swiftly fiscally pitilessly ...
RBR: adverb, comparative
    further gloomier grander graver greater grimmer harder harsher
    healthier heavier higher however larger later leaner lengthier less-
    perfectly lesser lonelier longer louder lower more ...
RBS: adverb, superlative
    best biggest bluntest earliest farthest first furthest hardest
    heartiest highest largest least less most nearest second tightest worst
RP: particle
    aboard about across along apart around aside at away back before behind
    by crop down ever fast for forth from go high i.e. in into just later
    low more off on open out over per pie raising start teeth that through
    under unto up up-pp upon whole with you
SYM: symbol
    % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***
TO: "to" as preposition or infinitive marker
    to
UH: interjection
    Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
    huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
    man baby diddle hush sonuvabitch ...
VB: verb, base form
    ask assemble assess assign assume atone attention avoid bake balkanize
    bank begin behold believe bend benefit bevel beware bless boil bomb
    boost brace break bring broil brush build ...
VBD: verb, past tense
    dipped pleaded swiped regummed soaked tidied convened halted registered
    cushioned exacted snubbed strode aimed adopted belied figgered
    speculated wore appreciated contemplated ...
VBG: verb, present participle or gerund
    telegraphing stirring focusing angering judging stalling lactating
    hankerin' alleging veering capping approaching traveling besieging
    encrypting interrupting erasing wincing ...
VBN: verb, past participle
    multihulled dilapidated aerosolized chaired languished panelized used
    experimented flourished imitated reunifed factored condensed sheared
    unsettled primed dubbed desired ...
VBP: verb, present tense, not 3rd person singular
    predominate wrap resort sue twist spill cure lengthen brush terminate
    appear tend stray glisten obtain comprise detest tease attract
    emphasize mold postpone sever return wag ...
VBZ: verb, present tense, 3rd person singular
    bases reconstructs marks mixes displeases seals carps weaves snatches
    slumps stretches authorizes smolders pictures emerges stockpiles
    seduces fizzes uses bolsters slaps speaks pleads ...
WDT: WH-determiner
    that what whatever which whichever
WP: WH-pronoun
    that what whatever whatsoever which who whom whosoever
WP$: WH-pronoun, possessive
    whose
WRB: Wh-adverb
    how however whence whenever where whereby whereever wherein whereof why
``: opening quotation mark
    ` ``

Patterns from Raw-Text Corpus#

import nltk
from nltk.corpus import gutenberg
gutenberg.fileids()
['austen-emma.txt',
 'austen-persuasion.txt',
 'austen-sense.txt',
 'bible-kjv.txt',
 'blake-poems.txt',
 'bryant-stories.txt',
 'burgess-busterbrown.txt',
 'carroll-alice.txt',
 'chesterton-ball.txt',
 'chesterton-brown.txt',
 'chesterton-thursday.txt',
 'edgeworth-parents.txt',
 'melville-moby_dick.txt',
 'milton-paradise.txt',
 'shakespeare-caesar.txt',
 'shakespeare-hamlet.txt',
 'shakespeare-macbeth.txt',
 'whitman-leaves.txt']
alice_sents = [ ' '.join(sent) 
               for sent in gutenberg.sents(fileids='carroll-alice.txt')
              if len(sent)>=5]
alice_sents[:5]
["[ Alice ' s Adventures in Wonderland by Lewis Carroll 1865 ]",
 'Down the Rabbit - Hole',
 "Alice was beginning to get very tired of sitting by her sister on the bank , and of having nothing to do : once or twice she had peeped into the book her sister was reading , but it had no pictures or conversations in it , ' and what is the use of a book ,' thought Alice ' without pictures or conversation ?'",
 'So she was considering in her own mind ( as well as she could , for the hot day made her feel very sleepy and stupid ), whether the pleasure of making a daisy - chain would be worth the trouble of getting up and picking the daisies , when suddenly a White Rabbit with pink eyes ran close by her .',
 "There was nothing so VERY remarkable in that ; nor did Alice think it so VERY much out of the way to hear the Rabbit say to itself , ' Oh dear !"]
import re

all_matches= [re.findall(r'(?:have|has)(?: [^s]+){0,2}[^\s]+(?:en|ed)', sent) for sent in alice_sents]
print([m for m in all_matches if len(m)!=0])
[['have wondered'], ['have been changed'], ['have been changed'], ['have dropped'], ['have changed'], ['have happened'], ['have liked'], ['have been changed'], ['have answered'], ['have got altered'], ['have called'], ['have to beat time when'], ["have done that , you know ,' Alice gently remarked ; ' they ' d have been"], ['have been'], ['have croqueted the Queen'], ['have everybody executed'], ['have any pepper in my kitchen'], ['have the experiment tried'], ['have been', 'have appeared'], ['have ordered'], ['have wanted'], ['have been'], ['have lived'], ['have no notion how delightful it will be When'], ['have baked'], ['have it explained'], ['have finished'], ['have you executed'], ['have you executed'], ['have you executed'], ['have been'], ['have imitated']]
  • The grouping parenthsis changes the behavior of re.findall()

  • With parenthesis, the regex engine automatically captures the matches in all the groups and return the results as a tuple.

  • Use (?:...) to create non-capturing gorups

match = re.findall(r'(?:is|was) (?:\w+ing)', '''
Alice was beginning to get very tired of sitting by her sister on the bank , 
and of having nothing to do : once or twice she had peeped into the book 
her sister was reading , but it had no pictures or conversations in it , 
and what is the use of a book , thought Alice  without pictures or conversation ?
''')


if match:
    for m in match:
        print(m.strip())
was beginning
was reading

Important

It seems that when we use re.findall(), the matches returned would only be the capturing groups; but when we use re.finditer(), it would return the whole match strings as well as every section of the capturing groups.

I would prefer re.finditer(). Otherwise, re.findall() may need to specify the non-capturing group (?:...).

pat_perfect = re.compile(r'(is|was) (\w+ing)')
text = '''
Alice was beginning to get very tired of sitting by her sister on the bank , 
and of having nothing to do : once or twice she had peeped into the book 
her sister was reading , but it had no pictures or conversations in it , 
and what is the use of a book , thought Alice  without pictures or conversation ?
'''

pat_perfect_matches = pat_perfect.finditer(text)

if pat_perfect_matches:
    for m in pat_perfect_matches:
        print(m.group())
was beginning
was reading