A simple API to scan and tokenize text for the purpose of structured language processing.
Project description
nr.parsing.core
The nr.parsing.core
package provides a simple API to scan and tokenize text for the purpose of
structured langauge processing.
Example
from nr.parsing.core import RuleSet, Tokenizer, rules
ruleset = RuleSet()
ruleset.rule('number', rules.regex_extract(r'\-?(0|[1-9]\d*)', 0))
ruleset.rule('operator', rules.regex_extract(r'[\-\+]', 0))
ruleset.rule('whitespace', rules.regex(r'\s+'), skip=True)
def calculate(expr: str) -> int:
tokenizer = Tokenizer(ruleset, expr)
result = 0
sign: t.Optional[int] = 1
while tokenizer:
if tokenizer.current.type != 'number':
raise ValueError(f'unexpected token {tokenizer.current}')
assert sign is not None
result += sign * int(tokenizer.current.value)
tokenizer.next()
if tokenizer.current.type == 'operator':
sign = -1 if tokenizer.current.value == '-' else 1
tokenizer.next()
else:
sign = None
if sign is not None:
raise ValueError(f'unexpected trailing operator')
return result
assert calculate('3 + 5 - 1') == 7
Copyright © 2020 Niklas Rosenstein
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
nr.parsing.core-2.0.0.tar.gz
(11.1 kB
view details)
Built Distribution
File details
Details for the file nr.parsing.core-2.0.0.tar.gz
.
File metadata
- Download URL: nr.parsing.core-2.0.0.tar.gz
- Upload date:
- Size: 11.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.1 setuptools/54.0.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0d89327a6b5daf40fdd8efefa1db35d558c87b18c096497577d44eb3f2fee800 |
|
MD5 | 85965bb2a228a50136e2efd7871570c7 |
|
BLAKE2b-256 | 06a89daa3a369b5a4b3f1785091d2d1425a020e78ef6a34860d86d39f5616edf |
File details
Details for the file nr.parsing.core-2.0.0-py3-none-any.whl
.
File metadata
- Download URL: nr.parsing.core-2.0.0-py3-none-any.whl
- Upload date:
- Size: 20.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.25.1 setuptools/54.0.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d77564542c5501386c1d03ed017bcd3be08c3465c48431e5a1bc91f4eee02e2b |
|
MD5 | e00a66e25ca3b4acb06af314bbb63dce |
|
BLAKE2b-256 | 6806663a25d5adeb16b0b67312715fa7a59aa28433989e73d9963a453df40837 |