mathparse 0.2.5__py3-none-any.whl → 0.2.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mathparse/__init__.py +1 -1
- mathparse/mathparse.py +79 -24
- mathparse-0.2.7.dist-info/METADATA +125 -0
- mathparse-0.2.7.dist-info/RECORD +8 -0
- mathparse-0.2.5.dist-info/METADATA +0 -69
- mathparse-0.2.5.dist-info/RECORD +0 -8
- {mathparse-0.2.5.dist-info → mathparse-0.2.7.dist-info}/WHEEL +0 -0
- {mathparse-0.2.5.dist-info → mathparse-0.2.7.dist-info}/licenses/LICENSE +0 -0
- {mathparse-0.2.5.dist-info → mathparse-0.2.7.dist-info}/top_level.txt +0 -0
mathparse/__init__.py
CHANGED
mathparse/mathparse.py
CHANGED
|
@@ -18,11 +18,13 @@ def is_int(string: str) -> bool:
|
|
|
18
18
|
"""
|
|
19
19
|
Return true if string is an integer.
|
|
20
20
|
"""
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
21
|
+
# Allow leading minus sign
|
|
22
|
+
if string[0] == '-':
|
|
23
|
+
# Must have at least one digit after the minus
|
|
24
|
+
return len(string) > 1 and string[1:].isdigit()
|
|
25
|
+
else:
|
|
26
|
+
# Must be all digits
|
|
27
|
+
return string.isdigit()
|
|
26
28
|
|
|
27
29
|
|
|
28
30
|
def is_float(string: str) -> bool:
|
|
@@ -79,6 +81,27 @@ def is_word(word: str, language: str) -> bool:
|
|
|
79
81
|
return word in words
|
|
80
82
|
|
|
81
83
|
|
|
84
|
+
def to_number(val) -> Union[int, float, str, Decimal]:
|
|
85
|
+
"""
|
|
86
|
+
Convert a string to an int or float if possible.
|
|
87
|
+
"""
|
|
88
|
+
# If already a number (int, float, Decimal), return as-is
|
|
89
|
+
if isinstance(val, (int, float, Decimal)):
|
|
90
|
+
return val
|
|
91
|
+
|
|
92
|
+
# Check if it's a constant and convert
|
|
93
|
+
if is_constant(val):
|
|
94
|
+
return mathwords.CONSTANTS[val]
|
|
95
|
+
|
|
96
|
+
# Otherwise, try to convert string to number
|
|
97
|
+
if is_int(val):
|
|
98
|
+
return int(val)
|
|
99
|
+
elif is_float(val):
|
|
100
|
+
return float(val)
|
|
101
|
+
|
|
102
|
+
return val
|
|
103
|
+
|
|
104
|
+
|
|
82
105
|
def create_unicode_word_boundary_pattern(word: str) -> str:
|
|
83
106
|
"""
|
|
84
107
|
Create a regex pattern with Unicode-aware word boundaries.
|
|
@@ -459,11 +482,11 @@ def to_postfix(tokens: list) -> list:
|
|
|
459
482
|
|
|
460
483
|
for token in tokens:
|
|
461
484
|
if is_int(token):
|
|
462
|
-
postfix.append(
|
|
485
|
+
postfix.append(token)
|
|
463
486
|
elif is_float(token):
|
|
464
|
-
postfix.append(
|
|
487
|
+
postfix.append(token)
|
|
465
488
|
elif token in mathwords.CONSTANTS:
|
|
466
|
-
postfix.append(
|
|
489
|
+
postfix.append(token)
|
|
467
490
|
elif is_unary(token):
|
|
468
491
|
opstack.append(token)
|
|
469
492
|
elif token == '(':
|
|
@@ -516,6 +539,8 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
|
|
|
516
539
|
stack.append(token)
|
|
517
540
|
elif is_unary(token):
|
|
518
541
|
a = stack.pop()
|
|
542
|
+
# Convert token (string) to number for unary function evaluation
|
|
543
|
+
a = to_number(a)
|
|
519
544
|
total = mathwords.UNARY_FUNCTIONS[token](a)
|
|
520
545
|
elif len(stack) == 1:
|
|
521
546
|
raise PostfixTokenEvaluationException(
|
|
@@ -526,14 +551,15 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
|
|
|
526
551
|
elif len(stack) > 1:
|
|
527
552
|
b = stack.pop()
|
|
528
553
|
a = stack.pop()
|
|
554
|
+
|
|
529
555
|
if token == '+':
|
|
530
|
-
total = a + b
|
|
556
|
+
total = to_number(a) + to_number(b)
|
|
531
557
|
elif token == '-':
|
|
532
|
-
total = a - b
|
|
558
|
+
total = to_number(a) - to_number(b)
|
|
533
559
|
elif token == '*':
|
|
534
|
-
total = a * b
|
|
560
|
+
total = to_number(a) * to_number(b)
|
|
535
561
|
elif token == '^':
|
|
536
|
-
total = a ** b
|
|
562
|
+
total = to_number(a) ** to_number(b)
|
|
537
563
|
elif token == '/':
|
|
538
564
|
if Decimal(str(b)) == 0:
|
|
539
565
|
total = 'undefined'
|
|
@@ -543,19 +569,33 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
|
|
|
543
569
|
# Treat decimal points as a binary operator that combines the
|
|
544
570
|
# integer and fractional part of two numbers
|
|
545
571
|
# Example: 53 . 25 = 53.25, -3 . 5 = -3.5
|
|
546
|
-
|
|
547
|
-
|
|
572
|
+
|
|
573
|
+
# Convert b to number
|
|
574
|
+
numeric_b = to_number(b)
|
|
575
|
+
|
|
576
|
+
if numeric_b == 0:
|
|
577
|
+
# Convert a to number
|
|
578
|
+
numeric_a = to_number(a)
|
|
579
|
+
total = Decimal(numeric_a)
|
|
548
580
|
else:
|
|
549
|
-
#
|
|
550
|
-
|
|
581
|
+
# Check if 'a' has a negative sign (handles -0 case)
|
|
582
|
+
is_negative = str(a).startswith('-')
|
|
583
|
+
|
|
584
|
+
# Convert a to number for calculation
|
|
585
|
+
numeric_a = to_number(a)
|
|
586
|
+
|
|
587
|
+
# Count the digits in the original string b to preserve
|
|
588
|
+
# leading zeros (e.g., "01" has 2 digits, not 1)
|
|
589
|
+
digits = len(str(b))
|
|
551
590
|
divisor = 10 ** digits
|
|
552
|
-
fractional_part =
|
|
553
|
-
|
|
554
|
-
# not -2.5
|
|
555
|
-
|
|
556
|
-
|
|
591
|
+
fractional_part = numeric_b / divisor
|
|
592
|
+
|
|
593
|
+
# Handle negatives: -3 . 5 = -3.5, not -2.5
|
|
594
|
+
# Also -0 . 5 = -0.5 (check string since -0 == 0)
|
|
595
|
+
if is_negative:
|
|
596
|
+
total = numeric_a - fractional_part
|
|
557
597
|
else:
|
|
558
|
-
total =
|
|
598
|
+
total = numeric_a + fractional_part
|
|
559
599
|
else:
|
|
560
600
|
raise PostfixTokenEvaluationException(
|
|
561
601
|
'Unknown token "{}"'.format(token)
|
|
@@ -570,7 +610,16 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
|
|
|
570
610
|
'The postfix expression resulted in an empty stack'
|
|
571
611
|
)
|
|
572
612
|
|
|
573
|
-
|
|
613
|
+
result = stack.pop()
|
|
614
|
+
|
|
615
|
+
# Convert final result from string to number if needed
|
|
616
|
+
if isinstance(result, str):
|
|
617
|
+
if is_int(result):
|
|
618
|
+
result = int(result)
|
|
619
|
+
elif is_float(result):
|
|
620
|
+
result = float(result)
|
|
621
|
+
|
|
622
|
+
return result
|
|
574
623
|
|
|
575
624
|
|
|
576
625
|
def tokenize(string: str, language: str = None, escape: str = '___') -> list:
|
|
@@ -822,4 +871,10 @@ def extract_expression(dirty_string: str, language: str) -> str:
|
|
|
822
871
|
else:
|
|
823
872
|
end_index -= 1
|
|
824
873
|
|
|
825
|
-
|
|
874
|
+
result = ' '.join(tokens[start_index:end_index])
|
|
875
|
+
|
|
876
|
+
# Remove spaces around decimal points for cleaner output
|
|
877
|
+
# Replace " . " with "." to convert "-100 . 5" to "-100.5"
|
|
878
|
+
result = result.replace(' . ', '.')
|
|
879
|
+
|
|
880
|
+
return result
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mathparse
|
|
3
|
+
Version: 0.2.7
|
|
4
|
+
Summary: mathparse is a library for solving mathematical equations contained in strings
|
|
5
|
+
Author: Gunther Cox
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://mathparse.chatterbot.us
|
|
8
|
+
Project-URL: Repository, https://github.com/gunthercox/mathparse
|
|
9
|
+
Project-URL: Changelog, https://github.com/gunthercox/mathparse/releases
|
|
10
|
+
Keywords: mathparse,mathematics,math,nlp,calculator,expression-parser,eval-alternative,safe-eval,multilingual,natural-language,postfix-notation,reverse-polish-notation,rpn,math-parser,expression-evaluator,secure-evaluation,language-processing,mathematical-expressions,formula-parser
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
+
Classifier: Topic :: Text Processing :: General
|
|
17
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
18
|
+
Classifier: Programming Language :: Python
|
|
19
|
+
Requires-Python: <3.15,>=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: flake8; extra == "test"
|
|
24
|
+
Requires-Dist: sphinx<9.0,>=7.4; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# mathparse
|
|
28
|
+
|
|
29
|
+
**A secure, multilingual mathematical expression evaluator for Python**
|
|
30
|
+
|
|
31
|
+
`mathparse` is a Python library that safely parses and evaluates mathematical expressions from strings, supporting both numeric operators and natural language words across 13+ languages. Unlike Python's dangerous `eval()` function, mathparse provides a secure, zero-dependency solution for evaluating user-provided mathematical expressions.
|
|
32
|
+
|
|
33
|
+
## Why mathparse?
|
|
34
|
+
|
|
35
|
+
✅ **Security First** - Never uses `eval()`, protecting against arbitrary code execution
|
|
36
|
+
✅ **Multilingual Support** - Parse math in English, Spanish, French, German, Chinese, and 8+ more languages
|
|
37
|
+
✅ **Zero Dependencies** - Pure Python implementation with no external requirements
|
|
38
|
+
✅ **Natural Language** - Understands "fifty times twenty plus ten" alongside standard notation
|
|
39
|
+
✅ **Production Ready** - Used in chatbots, calculators, voice assistants, and educational applications
|
|
40
|
+
✅ **Well Tested** - Comprehensive test suite ensuring reliability
|
|
41
|
+
|
|
42
|
+
## Quick Examples
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from mathparse import mathparse
|
|
46
|
+
|
|
47
|
+
# Standard numeric expressions
|
|
48
|
+
mathparse.parse('50 * (85 / 100)')
|
|
49
|
+
>>> 42.5
|
|
50
|
+
|
|
51
|
+
# Natural language in English
|
|
52
|
+
mathparse.parse('one hundred times fifty four', language='ENG')
|
|
53
|
+
>>> 5400
|
|
54
|
+
|
|
55
|
+
# Mixed notation
|
|
56
|
+
mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
|
|
57
|
+
>>> 24
|
|
58
|
+
|
|
59
|
+
# Other languages (French, Spanish, German, Chinese, etc.)
|
|
60
|
+
mathparse.parse('cinq plus trois', language='FRE')
|
|
61
|
+
>>> 8
|
|
62
|
+
|
|
63
|
+
mathparse.parse('cinco más tres', language='ESP')
|
|
64
|
+
>>> 8
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Use Cases
|
|
68
|
+
|
|
69
|
+
- 🤖 **Chatbots & Voice Assistants** - Parse natural language math queries
|
|
70
|
+
- 🧮 **Calculator Applications** - Build safe calculators that accept text input
|
|
71
|
+
- 📚 **Educational Software** - Evaluate student-provided math expressions
|
|
72
|
+
- 🌐 **Multilingual Apps** - Support math parsing in users' native languages
|
|
73
|
+
- 🔐 **Secure Code Evaluation** - Replace dangerous `eval()` calls with safe parsing
|
|
74
|
+
- 📊 **Data Processing** - Extract and calculate values from natural language text
|
|
75
|
+
|
|
76
|
+
## Security: Why Not eval()?
|
|
77
|
+
|
|
78
|
+
Python's `eval()` function executes arbitrary code, creating severe security vulnerabilities:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
# DANGEROUS - Never do this with user input!
|
|
82
|
+
eval("__import__('os').system('rm -rf /')") # Deletes files
|
|
83
|
+
eval("__import__('requests').get('evil.com')") # Network access
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**mathparse is the safe alternative:**
|
|
87
|
+
|
|
88
|
+
| Feature | eval() | mathparse |
|
|
89
|
+
|---------|--------|-----------|
|
|
90
|
+
| Mathematical expressions | ✅ | ✅ |
|
|
91
|
+
| Arbitrary code execution | ⚠️ **YES - DANGEROUS** | ❌ No |
|
|
92
|
+
| File system access | ⚠️ **YES - DANGEROUS** | ❌ No |
|
|
93
|
+
| Network access | ⚠️ **YES - DANGEROUS** | ❌ No |
|
|
94
|
+
| Import statements | ⚠️ **YES - DANGEROUS** | ❌ No |
|
|
95
|
+
| Security risk | 🔴 **CRITICAL** | 🟢 Safe |
|
|
96
|
+
| Dependencies | 0 | 0 |
|
|
97
|
+
| Natural language support | ❌ No | ✅ Yes |
|
|
98
|
+
| Multilingual | ❌ No | ✅ 13+ languages |
|
|
99
|
+
|
|
100
|
+
mathparse uses [postfix (Reverse Polish) notation](https://mathparse.chatterbot.us/postfix/) internally, ensuring only valid mathematical operations are performed. See our [security documentation](https://mathparse.chatterbot.us/postfix/) for technical details.
|
|
101
|
+
|
|
102
|
+
## Performance
|
|
103
|
+
|
|
104
|
+
- **Fast**: Simple numeric expressions parse in microseconds
|
|
105
|
+
- **Efficient**: Minimal memory footprint, suitable for high-volume applications
|
|
106
|
+
- **Scalable**: Linear time complexity for expression evaluation
|
|
107
|
+
|
|
108
|
+
## Language Support
|
|
109
|
+
|
|
110
|
+
The language parameter must be set in order to evaluate an equation that uses word operators.
|
|
111
|
+
The language code should be a valid [ISO 639-2](https://www.loc.gov/standards/iso639-2/php/code_list.php) language code.
|
|
112
|
+
|
|
113
|
+
## Installation
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pip install mathparse
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Documentation
|
|
120
|
+
|
|
121
|
+
See the full documentation at https://mathparse.chatterbot.us
|
|
122
|
+
|
|
123
|
+
## Changelog
|
|
124
|
+
|
|
125
|
+
See [release notes](https://github.com/gunthercox/mathparse/releases) for changes.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
mathparse/__init__.py,sha256=uTAXXEE3V31lunYRXe9wUM1iPWTh73dzfvCtnCoPwKM,110
|
|
2
|
+
mathparse/mathparse.py,sha256=KYuV1DIYxL4p7yscUZyQhOt_ucgH37icVvzmSfD73CM,31136
|
|
3
|
+
mathparse/mathwords.py,sha256=0SA6rG4X7lSRkhaHr-oIC1g6HFKCFJysqeyLASbALLo,48306
|
|
4
|
+
mathparse-0.2.7.dist-info/licenses/LICENSE,sha256=_buf4D_BxjT3x8SBhP0Rh966qP3zpbButcLI4bPq_TY,1068
|
|
5
|
+
mathparse-0.2.7.dist-info/METADATA,sha256=2dtwUiEp1fulXXcgnf8mPcn16sh4luiVA4RJscC3hxo,5156
|
|
6
|
+
mathparse-0.2.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
7
|
+
mathparse-0.2.7.dist-info/top_level.txt,sha256=rAQj3bfKyZhbFL6WxVLRCqnvwQPI2ZCc_FNrwx6Hlmc,10
|
|
8
|
+
mathparse-0.2.7.dist-info/RECORD,,
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: mathparse
|
|
3
|
-
Version: 0.2.5
|
|
4
|
-
Summary: mathparse is a library for solving mathematical equations contained in strings
|
|
5
|
-
Author: Gunther Cox
|
|
6
|
-
License-Expression: MIT
|
|
7
|
-
Project-URL: Documentation, https://mathparse.chatterbot.us
|
|
8
|
-
Project-URL: Repository, https://github.com/gunthercox/mathparse
|
|
9
|
-
Project-URL: Changelog, https://github.com/gunthercox/mathparse/releases
|
|
10
|
-
Keywords: mathparse,mathematics,math,nlp
|
|
11
|
-
Classifier: Development Status :: 4 - Beta
|
|
12
|
-
Classifier: Intended Audience :: Developers
|
|
13
|
-
Classifier: Operating System :: OS Independent
|
|
14
|
-
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
-
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
-
Classifier: Topic :: Text Processing :: General
|
|
17
|
-
Classifier: Topic :: Text Processing :: Linguistic
|
|
18
|
-
Classifier: Programming Language :: Python
|
|
19
|
-
Requires-Python: <3.14,>=3.9
|
|
20
|
-
Description-Content-Type: text/markdown
|
|
21
|
-
License-File: LICENSE
|
|
22
|
-
Provides-Extra: test
|
|
23
|
-
Requires-Dist: flake8; extra == "test"
|
|
24
|
-
Requires-Dist: sphinx<9.0,>=7.4; extra == "test"
|
|
25
|
-
Dynamic: license-file
|
|
26
|
-
|
|
27
|
-
# mathparse
|
|
28
|
-
|
|
29
|
-
The `mathparse` library is a Python module designed to evaluate mathematical equations contained in strings.
|
|
30
|
-
|
|
31
|
-
Here are a few examples:
|
|
32
|
-
|
|
33
|
-
```python
|
|
34
|
-
from mathparse import mathparse
|
|
35
|
-
|
|
36
|
-
mathparse.parse('50 * (85 / 100)')
|
|
37
|
-
>>> 42.5
|
|
38
|
-
|
|
39
|
-
mathparse.parse('one hundred times fifty four', language='ENG')
|
|
40
|
-
>>> 5400
|
|
41
|
-
|
|
42
|
-
mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
|
|
43
|
-
>>> 24
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
## Security
|
|
47
|
-
|
|
48
|
-
Mathparse does not employ the use of Python's [`eval` function](https://docs.python.org/3/library/functions.html#eval) when evaluating provided mathematical expressions. This is a measure to prevent arbitrary code execution vulnerabilities. See https://mathparse.chatterbot.us/postfix/ for additional details.
|
|
49
|
-
|
|
50
|
-
Mathparse is a standalone Python package and requires zero dependencies to function.
|
|
51
|
-
|
|
52
|
-
## Language Support
|
|
53
|
-
|
|
54
|
-
The language parameter must be set in order to evaluate an equation that uses word operators.
|
|
55
|
-
The language code should be a valid [ISO 639-2](https://www.loc.gov/standards/iso639-2/php/code_list.php) language code.
|
|
56
|
-
|
|
57
|
-
## Installation
|
|
58
|
-
|
|
59
|
-
```bash
|
|
60
|
-
pip install mathparse
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## Documentation
|
|
64
|
-
|
|
65
|
-
See the full documentation at https://mathparse.chatterbot.us
|
|
66
|
-
|
|
67
|
-
## Changelog
|
|
68
|
-
|
|
69
|
-
See [release notes](https://github.com/gunthercox/mathparse/releases) for changes.
|
mathparse-0.2.5.dist-info/RECORD
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
mathparse/__init__.py,sha256=ZBWkFcEyYlzjaH0qWeBIOxXUn9vIJOxbdpHpfXMtFTI,110
|
|
2
|
-
mathparse/mathparse.py,sha256=JNB33gr1dk_2pG_ftkcCrBBaoZHzWX_fQ-XLxStOjGw,29337
|
|
3
|
-
mathparse/mathwords.py,sha256=0SA6rG4X7lSRkhaHr-oIC1g6HFKCFJysqeyLASbALLo,48306
|
|
4
|
-
mathparse-0.2.5.dist-info/licenses/LICENSE,sha256=_buf4D_BxjT3x8SBhP0Rh966qP3zpbButcLI4bPq_TY,1068
|
|
5
|
-
mathparse-0.2.5.dist-info/METADATA,sha256=vy9LB508HGmsaNN6Ri62ncBacsVlaqLsRDO4538vn6c,2325
|
|
6
|
-
mathparse-0.2.5.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
7
|
-
mathparse-0.2.5.dist-info/top_level.txt,sha256=rAQj3bfKyZhbFL6WxVLRCqnvwQPI2ZCc_FNrwx6Hlmc,10
|
|
8
|
-
mathparse-0.2.5.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|