mathparse 0.2.5__tar.gz → 0.2.7__tar.gz

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.
Files changed (24) hide show
  1. mathparse-0.2.7/PKG-INFO +125 -0
  2. mathparse-0.2.7/README.md +99 -0
  3. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse/__init__.py +1 -1
  4. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse/mathparse.py +79 -24
  5. mathparse-0.2.7/mathparse.egg-info/PKG-INFO +125 -0
  6. {mathparse-0.2.5 → mathparse-0.2.7}/pyproject.toml +16 -1
  7. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_prefix_unary_operations.py +168 -2
  8. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_replace_word_tokens.py +20 -0
  9. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_utils.py +6 -0
  10. mathparse-0.2.5/PKG-INFO +0 -69
  11. mathparse-0.2.5/README.md +0 -43
  12. mathparse-0.2.5/mathparse.egg-info/PKG-INFO +0 -69
  13. {mathparse-0.2.5 → mathparse-0.2.7}/LICENSE +0 -0
  14. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse/mathwords.py +0 -0
  15. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse.egg-info/SOURCES.txt +0 -0
  16. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse.egg-info/dependency_links.txt +0 -0
  17. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse.egg-info/requires.txt +0 -0
  18. {mathparse-0.2.5 → mathparse-0.2.7}/mathparse.egg-info/top_level.txt +0 -0
  19. {mathparse-0.2.5 → mathparse-0.2.7}/setup.cfg +0 -0
  20. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_binary_operations.py +0 -0
  21. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_complex_statements.py +0 -0
  22. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_language_support.py +0 -0
  23. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_simplified_chinese.py +0 -0
  24. {mathparse-0.2.5 → mathparse-0.2.7}/tests/test_unary_operations.py +0 -0
@@ -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,99 @@
1
+ # mathparse
2
+
3
+ **A secure, multilingual mathematical expression evaluator for Python**
4
+
5
+ `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.
6
+
7
+ ## Why mathparse?
8
+
9
+ ✅ **Security First** - Never uses `eval()`, protecting against arbitrary code execution
10
+ ✅ **Multilingual Support** - Parse math in English, Spanish, French, German, Chinese, and 8+ more languages
11
+ ✅ **Zero Dependencies** - Pure Python implementation with no external requirements
12
+ ✅ **Natural Language** - Understands "fifty times twenty plus ten" alongside standard notation
13
+ ✅ **Production Ready** - Used in chatbots, calculators, voice assistants, and educational applications
14
+ ✅ **Well Tested** - Comprehensive test suite ensuring reliability
15
+
16
+ ## Quick Examples
17
+
18
+ ```python
19
+ from mathparse import mathparse
20
+
21
+ # Standard numeric expressions
22
+ mathparse.parse('50 * (85 / 100)')
23
+ >>> 42.5
24
+
25
+ # Natural language in English
26
+ mathparse.parse('one hundred times fifty four', language='ENG')
27
+ >>> 5400
28
+
29
+ # Mixed notation
30
+ mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
31
+ >>> 24
32
+
33
+ # Other languages (French, Spanish, German, Chinese, etc.)
34
+ mathparse.parse('cinq plus trois', language='FRE')
35
+ >>> 8
36
+
37
+ mathparse.parse('cinco más tres', language='ESP')
38
+ >>> 8
39
+ ```
40
+
41
+ ## Use Cases
42
+
43
+ - 🤖 **Chatbots & Voice Assistants** - Parse natural language math queries
44
+ - 🧮 **Calculator Applications** - Build safe calculators that accept text input
45
+ - 📚 **Educational Software** - Evaluate student-provided math expressions
46
+ - 🌐 **Multilingual Apps** - Support math parsing in users' native languages
47
+ - 🔐 **Secure Code Evaluation** - Replace dangerous `eval()` calls with safe parsing
48
+ - 📊 **Data Processing** - Extract and calculate values from natural language text
49
+
50
+ ## Security: Why Not eval()?
51
+
52
+ Python's `eval()` function executes arbitrary code, creating severe security vulnerabilities:
53
+
54
+ ```python
55
+ # DANGEROUS - Never do this with user input!
56
+ eval("__import__('os').system('rm -rf /')") # Deletes files
57
+ eval("__import__('requests').get('evil.com')") # Network access
58
+ ```
59
+
60
+ **mathparse is the safe alternative:**
61
+
62
+ | Feature | eval() | mathparse |
63
+ |---------|--------|-----------|
64
+ | Mathematical expressions | ✅ | ✅ |
65
+ | Arbitrary code execution | ⚠️ **YES - DANGEROUS** | ❌ No |
66
+ | File system access | ⚠️ **YES - DANGEROUS** | ❌ No |
67
+ | Network access | ⚠️ **YES - DANGEROUS** | ❌ No |
68
+ | Import statements | ⚠️ **YES - DANGEROUS** | ❌ No |
69
+ | Security risk | 🔴 **CRITICAL** | 🟢 Safe |
70
+ | Dependencies | 0 | 0 |
71
+ | Natural language support | ❌ No | ✅ Yes |
72
+ | Multilingual | ❌ No | ✅ 13+ languages |
73
+
74
+ 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.
75
+
76
+ ## Performance
77
+
78
+ - **Fast**: Simple numeric expressions parse in microseconds
79
+ - **Efficient**: Minimal memory footprint, suitable for high-volume applications
80
+ - **Scalable**: Linear time complexity for expression evaluation
81
+
82
+ ## Language Support
83
+
84
+ The language parameter must be set in order to evaluate an equation that uses word operators.
85
+ The language code should be a valid [ISO 639-2](https://www.loc.gov/standards/iso639-2/php/code_list.php) language code.
86
+
87
+ ## Installation
88
+
89
+ ```bash
90
+ pip install mathparse
91
+ ```
92
+
93
+ ## Documentation
94
+
95
+ See the full documentation at https://mathparse.chatterbot.us
96
+
97
+ ## Changelog
98
+
99
+ See [release notes](https://github.com/gunthercox/mathparse/releases) for changes.
@@ -2,4 +2,4 @@
2
2
  mathparse is a library for solving mathematical equations contained in strings
3
3
  """
4
4
 
5
- __version__ = '0.2.5'
5
+ __version__ = '0.2.7'
@@ -18,11 +18,13 @@ def is_int(string: str) -> bool:
18
18
  """
19
19
  Return true if string is an integer.
20
20
  """
21
- try:
22
- int(string)
23
- return True
24
- except ValueError:
25
- return False
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(int(token))
485
+ postfix.append(token)
463
486
  elif is_float(token):
464
- postfix.append(float(token))
487
+ postfix.append(token)
465
488
  elif token in mathwords.CONSTANTS:
466
- postfix.append(mathwords.CONSTANTS[token])
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
- if b == 0:
547
- total = Decimal(a)
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
- # Count the digits in b to determine the divisor
550
- digits = len(str(int(b)))
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 = b / divisor
553
- # Handle negative numbers correctly: -3 . 5 should be -3.5,
554
- # not -2.5
555
- if a < 0:
556
- total = a - fractional_part
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 = a + fractional_part
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
- return stack.pop()
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
- return ' '.join(tokens[start_index:end_index])
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.
@@ -12,7 +12,7 @@ version = {attr = "mathparse.__version__"}
12
12
 
13
13
  [project]
14
14
  name = "mathparse"
15
- requires-python = ">=3.9,<3.14"
15
+ requires-python = ">=3.9,<3.15"
16
16
  urls = { Documentation = "https://mathparse.chatterbot.us", Repository = "https://github.com/gunthercox/mathparse", Changelog = "https://github.com/gunthercox/mathparse/releases" }
17
17
  authors = [
18
18
  {name = "Gunther Cox"},
@@ -26,6 +26,21 @@ keywords = [
26
26
  "mathematics",
27
27
  "math",
28
28
  "nlp",
29
+ "calculator",
30
+ "expression-parser",
31
+ "eval-alternative",
32
+ "safe-eval",
33
+ "multilingual",
34
+ "natural-language",
35
+ "postfix-notation",
36
+ "reverse-polish-notation",
37
+ "rpn",
38
+ "math-parser",
39
+ "expression-evaluator",
40
+ "secure-evaluation",
41
+ "language-processing",
42
+ "mathematical-expressions",
43
+ "formula-parser",
29
44
  ]
30
45
  classifiers = [
31
46
  "Development Status :: 4 - Beta",
@@ -155,7 +155,13 @@ class NegativeWithUnaryFunctionsTestCase(TestCase):
155
155
  # Verify it causes the expected math error
156
156
  with self.assertRaises(ValueError) as context:
157
157
  mathparse.parse('sqrt -16')
158
- self.assertIn("math domain error", str(context.exception).lower())
158
+ # Python 3.14+ uses more specific error messages
159
+ error_msg = str(context.exception).lower()
160
+ self.assertTrue(
161
+ "math domain error" in error_msg or
162
+ "expected a nonnegative input" in error_msg,
163
+ f"Unexpected error message: {error_msg}"
164
+ )
159
165
 
160
166
  def test_log_with_negative_causes_math_error(self):
161
167
  """
@@ -168,7 +174,13 @@ class NegativeWithUnaryFunctionsTestCase(TestCase):
168
174
  # Verify it causes the expected math error
169
175
  with self.assertRaises(ValueError) as context:
170
176
  mathparse.parse('log -10')
171
- self.assertIn("math domain error", str(context.exception).lower())
177
+ # Python 3.14+ uses more specific error messages
178
+ error_msg = str(context.exception).lower()
179
+ self.assertTrue(
180
+ "math domain error" in error_msg or
181
+ "expected a positive input" in error_msg,
182
+ f"Unexpected error message: {error_msg}"
183
+ )
172
184
 
173
185
  def test_sqrt_with_positive_after_operator(self):
174
186
  """
@@ -231,6 +243,15 @@ class ExtractExpressionNegativeTestCase(TestCase):
231
243
  result = mathparse.extract_expression('5 - 3', language='ENG')
232
244
  self.assertEqual(result, '5 - 3')
233
245
 
246
+ def test_extract_negative_decimal(self):
247
+ """
248
+ Test: Extract leading negative decimal from sentence
249
+ """
250
+ result = mathparse.extract_expression(
251
+ 'What is -100.5 * 20?', language='ENG'
252
+ )
253
+ self.assertEqual(result, '-100.5 * 20')
254
+
234
255
  def test_extract_negative_in_parentheses_with_words(self):
235
256
  """
236
257
  Test: Extract expression with negative in parentheses from sentence
@@ -241,3 +262,148 @@ class ExtractExpressionNegativeTestCase(TestCase):
241
262
  # NOTE: Spaces are currently added, but ideally these will be removed
242
263
  # in the future
243
264
  self.assertEqual(result, '( -3 ) + 5')
265
+
266
+
267
+ class NegativeDecimalsLessThanOneTestCase(TestCase):
268
+ """
269
+ Test cases for negative decimal numbers between -1 and 0.
270
+
271
+ This addresses a bug where negative decimals less than 1
272
+ (e.g., -0.2, -0.5) were losing their negative sign during parsing.
273
+ The issue was caused by Python's -0 == 0 equality, where int('-0')
274
+ returns 0, losing sign information.
275
+ """
276
+
277
+ def test_negative_zero_point_two(self):
278
+ """
279
+ Test: -0.2 should equal -0.2
280
+ """
281
+ result = mathparse.parse('-0.2')
282
+ self.assertEqual(result, -0.2)
283
+
284
+ def test_negative_zero_point_five(self):
285
+ """
286
+ Test: -0.5 should equal -0.5
287
+ """
288
+ result = mathparse.parse('-0.5')
289
+ self.assertEqual(result, -0.5)
290
+
291
+ def test_negative_zero_point_nine(self):
292
+ """
293
+ Test: -0.9 should equal -0.9
294
+ """
295
+ result = mathparse.parse('-0.9')
296
+ self.assertEqual(result, -0.9)
297
+
298
+ def test_negative_zero_point_one(self):
299
+ """
300
+ Test: -0.1 should equal -0.1
301
+ """
302
+ result = mathparse.parse('-0.1')
303
+ self.assertEqual(result, -0.1)
304
+
305
+ def test_negative_zero_point_ninety_nine(self):
306
+ """
307
+ Test: -0.99 should equal -0.99"""
308
+ result = mathparse.parse('-0.99')
309
+ self.assertEqual(result, -0.99)
310
+
311
+ def test_negative_zero_point_zero_one(self):
312
+ """
313
+ Test: -0.01 should equal -0.01
314
+ """
315
+ result = mathparse.parse('-0.01')
316
+ self.assertEqual(result, -0.01)
317
+
318
+ def test_negative_zero_point_nine_nine_nine(self):
319
+ """
320
+ Test: -0.999 should equal -0.999
321
+ """
322
+ result = mathparse.parse('-0.999')
323
+ self.assertEqual(result, -0.999)
324
+
325
+ def test_negative_decimal_in_addition(self):
326
+ """
327
+ Test: -0.5 + 1 should equal 0.5
328
+ """
329
+ result = mathparse.parse('-0.5 + 1')
330
+ self.assertEqual(result, 0.5)
331
+
332
+ def test_negative_decimal_in_subtraction(self):
333
+ """
334
+ Test: 2 - -0.5 should equal 2.5
335
+ """
336
+ result = mathparse.parse('2 - -0.5')
337
+ self.assertEqual(result, 2.5)
338
+
339
+ def test_negative_decimal_in_multiplication(self):
340
+ """
341
+ Test: -0.5 * 4 should equal -2.0
342
+ """
343
+ result = mathparse.parse('-0.5 * 4')
344
+ self.assertEqual(result, -2.0)
345
+
346
+ def test_negative_decimal_in_division(self):
347
+ """
348
+ Test: -0.8 / 2 should equal -0.4
349
+ """
350
+ result = mathparse.parse('-0.8 / 2')
351
+ self.assertEqual(float(result), -0.4)
352
+
353
+ def test_multiple_negative_decimals(self):
354
+ """
355
+ Test: -0.3 + -0.2 should equal -0.5
356
+ """
357
+ result = mathparse.parse('-0.3 + -0.2')
358
+ self.assertAlmostEqual(result, -0.5, places=10)
359
+
360
+ def test_negative_decimal_with_parentheses(self):
361
+ """
362
+ Test: (-0.5) should equal -0.5
363
+ """
364
+ result = mathparse.parse('(-0.5)')
365
+ self.assertEqual(result, -0.5)
366
+
367
+ def test_negative_decimal_in_complex_expression(self):
368
+ """
369
+ Test: (-0.5 + 1) * 2 should equal 1.0
370
+ """
371
+ result = mathparse.parse('(-0.5 + 1) * 2')
372
+ self.assertEqual(result, 1.0)
373
+
374
+ def test_positive_decimals_still_work(self):
375
+ """
376
+ Test: 0.5 should equal 0.5
377
+ """
378
+ result = mathparse.parse('0.5')
379
+ self.assertEqual(result, 0.5)
380
+
381
+ def test_negative_integers_still_work(self):
382
+ """
383
+ Test: -5 should equal -5
384
+ """
385
+ result = mathparse.parse('-5')
386
+ self.assertEqual(result, -5)
387
+
388
+ def test_negative_decimals_greater_than_one_still_work(self):
389
+ """
390
+ Test: -1.5 should equal -1.5
391
+ """
392
+ result = mathparse.parse('-1.5')
393
+ self.assertEqual(result, -1.5)
394
+
395
+ def test_temperature_conversion_use_case(self):
396
+ """
397
+ -0.2 Celsius to Fahrenheit formula: (-0.2 * 9/5) + 32 = 31.64
398
+ (Example calculation)
399
+ """
400
+ result = mathparse.parse('-0.2 * 9 / 5 + 32')
401
+ self.assertAlmostEqual(float(result), 31.64, places=2)
402
+
403
+ def test_financial_calculation_use_case(self):
404
+ """
405
+ Balance: $100, transaction: -$0.25, expected: $99.75
406
+ (Example calculation)
407
+ """
408
+ result = mathparse.parse('100 + -0.25')
409
+ self.assertEqual(result, 99.75)
@@ -52,12 +52,32 @@ class EnglishWordTokenTestCase(TestCase):
52
52
  )
53
53
  self.assertEqual(result, '19 * (50 + 4)')
54
54
 
55
+ def test_tens_with_compound_numbers(self):
56
+ result = mathparse.replace_word_tokens(
57
+ 'ninety seven - 7', language='ENG'
58
+ )
59
+ self.assertEqual(result, '(90 + 7) - 7')
60
+
61
+ def test_tens_with_compound_numbers_hyphenated(self):
62
+ result = mathparse.replace_word_tokens(
63
+ 'ninety-seven - 7', language='ENG'
64
+ )
65
+ self.assertEqual(result, '(90 + 7) - 7')
66
+
55
67
  def test_tens_and_hundreds_with_spaces(self):
56
68
  result = mathparse.replace_word_tokens(
57
69
  'one hundred times fifty four', language='ENG'
58
70
  )
59
71
  self.assertEqual(result, '(1 * 100) * (50 + 4)')
60
72
 
73
+ def test_tens_with_hundreds_multiplier(self):
74
+ result = mathparse.replace_word_tokens(
75
+ 'eighteen hundred and twenty-one',
76
+ language='ENG',
77
+ stopwords={'and'}
78
+ )
79
+ self.assertEqual(result, '(18 * 100) + (20 + 1)')
80
+
61
81
  def test_hyphenated_numbers(self):
62
82
  result = mathparse.replace_word_tokens(
63
83
  'one hundred times fifty-four', language='ENG'
@@ -11,12 +11,18 @@ class BooleanChecksTestCase(TestCase):
11
11
  def test_is_not_integer(self):
12
12
  self.assertFalse(mathparse.is_int('42.2'))
13
13
 
14
+ def test_is_not_integer_negative(self):
15
+ self.assertFalse(mathparse.is_int('-42.2'))
16
+
14
17
  def test_is_float(self):
15
18
  self.assertTrue(mathparse.is_float('0.5'))
16
19
 
17
20
  def test_is_not_float(self):
18
21
  self.assertFalse(mathparse.is_float('5'))
19
22
 
23
+ def test_is_not_float_negative(self):
24
+ self.assertTrue(mathparse.is_float('-0.5'))
25
+
20
26
  def test_is_constant(self):
21
27
  self.assertTrue(mathparse.is_constant('pi'))
22
28
 
mathparse-0.2.5/PKG-INFO DELETED
@@ -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/README.md DELETED
@@ -1,43 +0,0 @@
1
- # mathparse
2
-
3
- The `mathparse` library is a Python module designed to evaluate mathematical equations contained in strings.
4
-
5
- Here are a few examples:
6
-
7
- ```python
8
- from mathparse import mathparse
9
-
10
- mathparse.parse('50 * (85 / 100)')
11
- >>> 42.5
12
-
13
- mathparse.parse('one hundred times fifty four', language='ENG')
14
- >>> 5400
15
-
16
- mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
17
- >>> 24
18
- ```
19
-
20
- ## Security
21
-
22
- 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.
23
-
24
- Mathparse is a standalone Python package and requires zero dependencies to function.
25
-
26
- ## Language Support
27
-
28
- The language parameter must be set in order to evaluate an equation that uses word operators.
29
- The language code should be a valid [ISO 639-2](https://www.loc.gov/standards/iso639-2/php/code_list.php) language code.
30
-
31
- ## Installation
32
-
33
- ```bash
34
- pip install mathparse
35
- ```
36
-
37
- ## Documentation
38
-
39
- See the full documentation at https://mathparse.chatterbot.us
40
-
41
- ## Changelog
42
-
43
- See [release notes](https://github.com/gunthercox/mathparse/releases) for changes.
@@ -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.
File without changes
File without changes