grammar for names

19 views
Skip to first unread message

raghavan

unread,
Apr 7, 2014, 4:39:50 PM4/7/14
to modgr...@googlegroups.com
Hi,

I'm new to modgrammar, and I'm trying to write a set of rules to recognize names. I have this:


class FirstName (Grammar):
    grammar = (WORD("A-Z", "a-z"))

class LastName (Grammar):
    grammar = (WORD("A-Z", "a-z"))

class Name (Grammar):
    grammar = (FirstName, OPTIONAL(LastName))

myparser = MyGrammar.parser()
results = myparser.parse_string("John" Smith)

from modgrammar import *


class FirstName (Grammar):
    grammar = (WORD("A-Z", "a-z"))

class LastName (Grammar):
    grammar = (WORD("A-Z", "a-z"))

class Name (Grammar):
    grammar = (FirstName, OPTIONAL(LastName))


myparser = Name.parser()
results = myparser.parse_text("John")
results.find_all(FirstName)

However, I get an error: AttributeError: 'NoneType' object has no attribute 'find_all'

Any help would be appreciated!

Alex Stewart

unread,
Apr 9, 2014, 5:03:34 PM4/9/14
to modgr...@googlegroups.com
Hi Raghavan,

You are getting the AttributeError because parse_text has returned None instead of a match object.  As mentioned in the docs for parse_text (https://pythonhosted.org/modgrammar/libref.html?highlight=parse_text#modgrammar.GrammarParser.parse_text):

If there is an incomplete match (or it is impossible to determine yet whether the match is complete or not), save the current text in the match buffer and return None to indicate more text is required.

That is, parse_text is returning None because it cannot be sure whether there is more input coming which might continue the matched expression (for example, you might call parse_text again when you get more input, and the extra input could be a last name).

This is one of the main differences between parse_text and parse_string.  parse_string will assume that what you're giving it is the complete text, and there isn't any more coming, so it will return the match if there is one.  parse_text is designed to be able to be called possibly multiple times as more input becomes available, and so cannot be sure it has reached the end unless you tell it.

What you probably want to do here is either to use parse_string instead (which is probably what you want), or alternately to call parse_text with the "eof=True" argument to tell it there's no more input coming.

--Alex



--
You received this message because you are subscribed to the Google Groups "modgrammar" group.
To unsubscribe from this group and stop receiving emails from it, send an email to modgrammar+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

raghavan

unread,
Apr 10, 2014, 1:12:42 PM4/10/14
to modgr...@googlegroups.com
Thanks that worked!
Reply all
Reply to author
Forward
0 new messages