Skip to content

Commit

Permalink
Hello world example.
Browse files Browse the repository at this point in the history
  • Loading branch information
eerimoq committed Jul 25, 2018
1 parent 42a9a31 commit ad38ac2
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 1 deletion.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ install:
script:
- coverage run --source=textparser setup.py test
- make test-sdist
- env PYTHONPATH=. python examples/hello_world.py
- env PYTHONPATH=. python examples/benchmarks/json/main.py
after_success:
coveralls
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ test:
python2 setup.py test
python3 setup.py test
$(MAKE) test-sdist
env PYTHONPATH=. python3 examples/hello_world.py
env PYTHONPATH=. python3 examples/benchmarks/json/main.py
codespell -d $$(git ls-files | grep -v \.json)

Expand Down
40 changes: 39 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,44 @@ Installation
Example usage
=============

To be added.
The `hello world`_ example parses the string ``Hello, World!`` and
outputs its parse tree ``['Hello', ',', 'World', '!']``.

The script:

.. code-block:: python
import textparser
from textparser import Sequence
from textparser import Grammar
class Parser(textparser.Parser):
def token_specs(self):
return [
('SKIP', r'[ \r\n\t]+'),
('WORD', r'\w+'),
('EMARK', '!', r'!'),
('COMMA', ',', r','),
('MISMATCH', r'.')
]
def grammar(self):
return Grammar(Sequence('WORD', ',', 'WORD', '!'))
tree = Parser().parse('Hello, World!')
print('Tree:', tree)
Executing the script:

.. code-block::
$ python3 examples/hello_world.py
Tree: ['Hello', ',', 'World', '!']
$
Contributing
============
Expand Down Expand Up @@ -64,3 +101,4 @@ Contributing
.. _pretty fast: https://github.com/eerimoq/textparser/blob/master/examples/benchmarks/json/main.py#L15-L25
.. _PyParsing: https://github.com/pyparsing/pyparsing
.. _Lark: https://github.com/lark-parser/lark
.. _hello world: https://github.com/eerimoq/textparser/blob/master/examples/hello_world.py
23 changes: 23 additions & 0 deletions examples/hello_world.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import textparser
from textparser import Sequence
from textparser import Grammar


class Parser(textparser.Parser):

def token_specs(self):
return [
('SKIP', r'[ \r\n\t]+'),
('WORD', r'\w+'),
('EMARK', '!', r'!'),
('COMMA', ',', r','),
('MISMATCH', r'.')
]

def grammar(self):
return Grammar(Sequence('WORD', ',', 'WORD', '!'))


tree = Parser().parse('Hello, World!')

print('Tree:', tree)

0 comments on commit ad38ac2

Please sign in to comment.