mathparse 0.2.1__py3-none-any.whl → 0.2.3__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 CHANGED
@@ -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.1'
5
+ __version__ = '0.2.3'
mathparse/mathparse.py CHANGED
@@ -2,19 +2,19 @@
2
2
  Methods for evaluating mathematical equations in strings.
3
3
  """
4
4
  from decimal import Decimal
5
+ from typing import Union
5
6
  from . import mathwords
6
7
  import re
7
8
 
8
9
 
9
10
  class PostfixTokenEvaluationException(Exception):
10
11
  """
11
- Exception to be raised when a language code is given that
12
- is not a part of the ISO 639-2 standard.
12
+ Exception to be raised when an expression cannot be evaluated.
13
13
  """
14
14
  pass
15
15
 
16
16
 
17
- def is_int(string):
17
+ def is_int(string: str) -> bool:
18
18
  """
19
19
  Return true if string is an integer.
20
20
  """
@@ -25,7 +25,7 @@ def is_int(string):
25
25
  return False
26
26
 
27
27
 
28
- def is_float(string):
28
+ def is_float(string: str) -> bool:
29
29
  """
30
30
  Return true if the string is a float.
31
31
  """
@@ -36,14 +36,14 @@ def is_float(string):
36
36
  return False
37
37
 
38
38
 
39
- def is_constant(string):
39
+ def is_constant(string: str) -> bool:
40
40
  """
41
41
  Return true if the string is a mathematical constant.
42
42
  """
43
43
  return mathwords.CONSTANTS.get(string, False)
44
44
 
45
45
 
46
- def is_unary(string):
46
+ def is_unary(string: str) -> bool:
47
47
  """
48
48
  Return true if the string is a defined unary mathematical
49
49
  operator function.
@@ -51,14 +51,14 @@ def is_unary(string):
51
51
  return string in mathwords.UNARY_FUNCTIONS
52
52
 
53
53
 
54
- def is_binary(string):
54
+ def is_binary(string: str) -> bool:
55
55
  """
56
56
  Return true if the string is a defined binary operator.
57
57
  """
58
58
  return string in mathwords.BINARY_OPERATORS
59
59
 
60
60
 
61
- def is_symbol(string):
61
+ def is_symbol(string: str) -> bool:
62
62
  """
63
63
  Return true if the string is a mathematical symbol.
64
64
  """
@@ -70,7 +70,7 @@ def is_symbol(string):
70
70
  )
71
71
 
72
72
 
73
- def is_word(word, language):
73
+ def is_word(word: str, language: str) -> bool:
74
74
  """
75
75
  Return true if the word is a math word for the specified language.
76
76
  """
@@ -79,7 +79,7 @@ def is_word(word, language):
79
79
  return word in words
80
80
 
81
81
 
82
- def find_word_groups(string, words):
82
+ def find_word_groups(string: str, words: list) -> list:
83
83
  """
84
84
  Find matches for words in the format "3 thousand 6 hundred 2".
85
85
  The words parameter should be the list of words to check for
@@ -98,40 +98,235 @@ def find_word_groups(string, words):
98
98
  return result
99
99
 
100
100
 
101
- def replace_word_tokens(string, language):
101
+ def replace_word_tokens_simplified_chinese(
102
+ string, stopwords: set[str] = None
103
+ ) -> str:
102
104
  """
105
+ simplified Chinese version:
103
106
  Given a string and an ISO 639-2 language code,
104
107
  return the string with the words replaced with
105
108
  an operational equivalent.
106
109
  """
107
- words = mathwords.word_groups_for_language(language)
110
+ words = mathwords.word_groups_for_language('CHI')
111
+
112
+ # Handle special Chinese power construction patterns FIRST
113
+ # In Chinese, '的...次方' forms a power construction where:
114
+ # - '的' acts as a possessive/linking word (provides the ^ operator)
115
+ # - '次方' is a suffix meaning "power" (should be removed, not replaced)
116
+ # - '次幂' is similar to '次方'
117
+ # Example: 二的四次方 = 2's 4th power = 2 ^ 4
118
+ # We need to remove '次方' and '次幂' BEFORE they get replaced as operators
119
+ string = string.replace('次方', ' ')
120
+ string = string.replace('次幂', ' ')
121
+
122
+ # Collect all operators (binary, prefix unary, postfix unary)
123
+ # and process them by length (longest first) to handle cases where
124
+ # a shorter operator is a substring of a longer one
125
+ # Example: '平方' (squared) vs '平方根' (square root)
126
+ all_operators = {}
127
+
128
+ # Add binary operators
129
+ all_operators.update(words['binary_operators'])
130
+
131
+ # Add prefix unary operators
132
+ all_operators.update(words['prefix_unary_operators'])
133
+
134
+ # Add postfix unary operators
135
+ if 'postfix_unary_operators' in words:
136
+ all_operators.update(words['postfix_unary_operators'])
137
+
138
+ # Sort all operators by length (longest first)
139
+ sorted_operators = sorted(all_operators.keys(), key=len, reverse=True)
140
+
141
+ for operator in sorted_operators:
142
+ if operator in string:
143
+ # 中文没有分隔符,后面需要靠分隔符分割式子,每次识别一个符号都将其分开来
144
+ string = string.replace(
145
+ operator, ' ' + all_operators[operator] + ' '
146
+ )
147
+
148
+ # chinese_scales用list的原因是为了保持从大到小的顺序,亿、万、千...
149
+ # Sort scales by their numeric value (largest first) to ensure correct
150
+ # parsing. For example, '千' (1000) should be found before '百' (100)
151
+ digits = set(words['numbers'].keys())
152
+ scales = sorted(
153
+ words['scales'].keys(), key=lambda x: words['scales'][x], reverse=True
154
+ )
155
+ digits_scales = words['numbers'].copy()
156
+ digits_scales.update(words['scales'])
157
+
158
+ # 九千八百万九千八百——> 98009800
159
+ def chinese_string_to_num(str):
160
+ if str == '':
161
+ return 0
162
+
163
+ if str in digits:
164
+ return digits_scales[str]
165
+
166
+ digits_scales.update(words['scales'])
167
+
168
+ for scale in scales:
169
+ index = str.find(scale)
170
+ if index >= 0:
171
+ t1 = chinese_string_to_num(str[:index])
172
+ t2 = digits_scales[scale]
173
+ t3 = chinese_string_to_num(str[index + 1:])
174
+ return t1 * t2 + t3
175
+ else:
176
+ return digits_scales[str]
177
+
178
+ # 扫描看有没有汉字数字,有转化为阿拉伯数字
179
+ index = 0
180
+ start = end = 0
181
+ while True:
182
+ char = string[index]
183
+
184
+ if char in digits_scales:
185
+ end += 1
186
+ index += 1
187
+ else:
188
+ if start < end:
189
+ num = str(chinese_string_to_num(string[start:end]))
190
+ # 需要加多一个分隔符
191
+ num_str = str(num) + ' '
192
+ string = string[:start] + num_str + string[end:]
193
+ index = start + len(num_str)
194
+ start = end = index
195
+ else:
196
+ index += 1
197
+ start = end = index
198
+
199
+ if index >= len(string):
200
+ if start < end:
201
+ num = str(chinese_string_to_num(string[start:end]))
202
+ num_str = str(num) + ' '
203
+ string = string[:start] + num_str + string[end:]
204
+
205
+ break
206
+
207
+ return string
208
+
209
+
210
+ def replace_word_tokens(
211
+ string: str, language: str, stopwords: set[str] = None
212
+ ) -> str:
213
+ """
214
+ Replace word-based mathematical terms with their symbolic equivalents.
215
+
216
+ Given a string and an ISO 639-2 language code,
217
+ return the string with the words replaced with
218
+ an operational equivalent.
108
219
 
109
- # Replace operator words with numeric operators
110
- operators = words['binary_operators'].copy()
111
- if 'unary_operators' in words:
112
- operators.update(words['unary_operators'])
220
+ Args:
221
+ string (str): The input string containing a mathematical expression
222
+ with words.
223
+
224
+ language (str): ISO 639-2 language code for word-based parsing.
225
+
226
+ stopwords (set[str], optional): A set of words to ignore during
227
+ parsing. This can be used to filter out
228
+ non-mathematical words in expressions.
229
+
230
+ Returns:
231
+ str: The input string with word-based mathematical terms replaced
232
+ with their symbolic equivalents.
233
+ """
234
+ words = mathwords.word_groups_for_language(language)
113
235
 
114
- for operator in list(operators.keys()):
236
+ # Process operators by length (longest first) to handle compound operators
237
+ binary_operators = words['binary_operators']
238
+ sorted_operators = sorted(binary_operators.keys(), key=len, reverse=True)
239
+ for operator in sorted_operators:
115
240
  if operator in string:
116
- string = string.replace(operator, operators[operator])
241
+ string = string.replace(operator, binary_operators[operator])
242
+
243
+ # Handle prefix unary operators (like "square root of")
244
+ if 'prefix_unary_operators' in words:
245
+ prefix_unary_operators = words['prefix_unary_operators']
246
+ # Sort by length to handle compound operators where a shorter token
247
+ # is a substring of a longer token
248
+ sorted_prefix_operators = sorted(
249
+ prefix_unary_operators.keys(), key=len, reverse=True
250
+ )
251
+ for operator in sorted_prefix_operators:
252
+ if operator in string:
253
+ string = string.replace(
254
+ operator, prefix_unary_operators[operator]
255
+ )
117
256
 
118
- # Replace number words with numeric values
257
+ # Handle postfix unary operators (like "squared", "cubed")
258
+ if 'postfix_unary_operators' in words:
259
+ postfix_unary_operators = words['postfix_unary_operators']
260
+ # Sort by length to handle compound operators where a shorter token
261
+ # is a substring of a longer token
262
+ sorted_postfix_operators = sorted(
263
+ postfix_unary_operators.keys(), key=len, reverse=True
264
+ )
265
+ for operator in sorted_postfix_operators:
266
+ if operator in string:
267
+ # Captures the number/operand before the unary operator
268
+ pattern = r'(\w+)\s+' + re.escape(operator)
269
+ replacement = r'(\1 ' + postfix_unary_operators[operator] + ')'
270
+ string = re.sub(pattern, replacement, string)
271
+
272
+ # Handle compound numbers:
273
+ # (e.g., "twenty one" -> "(20 + 1)", "fifty four" -> "(50 + 4)")
119
274
  numbers = words['numbers']
120
- for number in list(numbers.keys()):
121
- if number in string:
122
- string = string.replace(number, str(numbers[number]))
275
+
276
+ # Create regex patterns for compound numbers
277
+ # Pattern matches: (tens_word) (units_word) where tens_word is
278
+ # 20,30,40,...,90 and units_word is 1-9
279
+ tens_words = {word: value for word, value in numbers.items() if value in [
280
+ 20, 30, 40, 50, 60, 70, 80, 90
281
+ ]}
282
+ units_words = {word: value for word, value in numbers.items() if value in [
283
+ 1, 2, 3, 4, 5, 6, 7, 8, 9
284
+ ]}
285
+
286
+ # Preprocess hyphenated compound numbers
287
+ # (e.g., "fifty-four" -> "fifty four")
288
+ for tens_word in tens_words.keys():
289
+ for units_word in units_words.keys():
290
+ hyphenated_pattern = tens_word + r'-' + units_word
291
+ space_separated = tens_word + ' ' + units_word
292
+ if re.search(hyphenated_pattern, string):
293
+ string = re.sub(hyphenated_pattern, space_separated, string)
294
+
295
+ # Replace compound numbers first (before individual number replacement)
296
+ for tens_word, tens_value in tens_words.items():
297
+ for units_word, units_value in units_words.items():
298
+ compound_pattern = tens_word + r'\s+' + units_word
299
+ compound_replacement = f'({tens_value} + {units_value})'
300
+ if re.search(compound_pattern, string):
301
+ string = re.sub(compound_pattern, compound_replacement, string)
302
+
303
+ # Replace number words with numeric values
304
+ for number in frozenset(numbers.keys()):
305
+ # Use word boundaries to prevent partial matches
306
+ # (e.g., "nine" in "nineteen")
307
+ pattern = r'\b' + re.escape(number) + r'\b'
308
+ if re.search(pattern, string):
309
+ string = re.sub(pattern, str(numbers[number]), string)
310
+
311
+ # Remove words specified to be ignored
312
+ if stopwords:
313
+ filtered_words = []
314
+
315
+ for word in string.split():
316
+ if word not in stopwords:
317
+ filtered_words.append(word)
318
+ string = ' '.join(filtered_words)
123
319
 
124
320
  # Replace scaling multipliers with numeric values
125
321
  scales = words['scales']
126
- end_index_characters = mathwords.BINARY_OPERATORS
127
- end_index_characters.add('(')
322
+ end_index_characters = mathwords.BINARY_OPERATORS | {'('}
128
323
 
129
- word_matches = find_word_groups(string, list(scales.keys()))
324
+ word_matches = find_word_groups(string, frozenset(scales.keys()))
130
325
 
131
326
  for match in word_matches:
132
327
  string = string.replace(match, '(' + match + ')')
133
328
 
134
- for scale in list(scales.keys()):
329
+ for scale in frozenset(scales.keys()):
135
330
  for _ in range(0, string.count(scale)):
136
331
  start_index = string.find(scale) - 1
137
332
  end_index = len(string)
@@ -154,10 +349,56 @@ def replace_word_tokens(string, language):
154
349
 
155
350
  string = string.replace(') (', ') + (')
156
351
 
352
+ # Remove extra parentheses around all scale expressions to simplify output
353
+ # Convert ((number * scale)) to (number * scale) for all scales
354
+ string = re.sub(r'\(\((\d+\s*\*\s*\d+)\)\)', r'(\1)', string)
355
+
157
356
  return string
158
357
 
159
358
 
160
- def to_postfix(tokens):
359
+ def preprocess_unary_operators(tokens: list) -> list:
360
+ """
361
+ Preprocess tokens to convert unary minus to the 'neg' function.
362
+
363
+ A minus sign is considered unary (negative) if it appears:
364
+ * At the beginning of the expression
365
+ * After an opening parenthesis '('
366
+ * After a binary operator `(+, -, *, /, ^)`
367
+ """
368
+ if not tokens:
369
+ return tokens
370
+
371
+ processed_tokens = []
372
+
373
+ binary_operators = mathwords.BINARY_OPERATORS | {'('}
374
+
375
+ for i, token in enumerate(tokens):
376
+ if token == '-':
377
+ # Check if this minus should be treated as unary
378
+ is_unary_minus = False
379
+
380
+ if i == 0:
381
+ # The first token is unary minus
382
+ is_unary_minus = True
383
+ elif i > 0:
384
+ prev_token = tokens[i - 1]
385
+ # A unary minus after opening parenthesis or binary operators
386
+ if prev_token in binary_operators:
387
+ is_unary_minus = True
388
+
389
+ if is_unary_minus:
390
+ # Convert the unary minus to 'neg' function
391
+ processed_tokens.append('neg')
392
+ else:
393
+ # Keep as binary minus
394
+ processed_tokens.append(token)
395
+ else:
396
+ processed_tokens.append(token)
397
+
398
+ return processed_tokens
399
+
400
+
401
+ def to_postfix(tokens: list) -> list:
161
402
  """
162
403
  Convert a list of evaluatable tokens to postfix format.
163
404
  """
@@ -170,6 +411,9 @@ def to_postfix(tokens):
170
411
  '(': 1
171
412
  }
172
413
 
414
+ # Unary functions have a higher precedence than binary operators
415
+ unary_precedence = max(precedence.values()) + 1
416
+
173
417
  postfix = []
174
418
  opstack = []
175
419
 
@@ -189,12 +433,28 @@ def to_postfix(tokens):
189
433
  while top_token != '(':
190
434
  postfix.append(top_token)
191
435
  top_token = opstack.pop()
192
- else:
436
+ elif is_binary(token):
437
+ # For binary operators, pop operators with higher or
438
+ # equal precedence
193
439
  while (opstack != []) and (
194
- precedence[opstack[-1]] >= precedence[token]
440
+ (
441
+ opstack[-1] in precedence and token in precedence and (
442
+ precedence[opstack[-1]] >= precedence[token]
443
+ )
444
+ ) or
445
+ (
446
+ is_unary(
447
+ opstack[-1]
448
+ ) and unary_precedence >= precedence[token]
449
+ )
195
450
  ):
196
451
  postfix.append(opstack.pop())
197
452
  opstack.append(token)
453
+ else:
454
+ # Raise exception for unsupported mathematical terms
455
+ raise PostfixTokenEvaluationException(
456
+ 'Unsupported mathematical term: "{}"'.format(token)
457
+ )
198
458
 
199
459
  while opstack != []:
200
460
  postfix.append(opstack.pop())
@@ -202,7 +462,7 @@ def to_postfix(tokens):
202
462
  return postfix
203
463
 
204
464
 
205
- def evaluate_postfix(tokens):
465
+ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
206
466
  """
207
467
  Given a list of evaluatable tokens in postfix format,
208
468
  calculate a solution.
@@ -217,7 +477,13 @@ def evaluate_postfix(tokens):
217
477
  elif is_unary(token):
218
478
  a = stack.pop()
219
479
  total = mathwords.UNARY_FUNCTIONS[token](a)
220
- elif len(stack):
480
+ elif len(stack) == 1:
481
+ raise PostfixTokenEvaluationException(
482
+ 'Insufficient values in expression for operator "{}"'.format(
483
+ token
484
+ )
485
+ )
486
+ elif len(stack) > 1:
221
487
  b = stack.pop()
222
488
  a = stack.pop()
223
489
  if token == '+':
@@ -235,7 +501,7 @@ def evaluate_postfix(tokens):
235
501
  total = Decimal(str(a)) / Decimal(str(b))
236
502
  else:
237
503
  raise PostfixTokenEvaluationException(
238
- 'Unknown token {}'.format(token)
504
+ 'Unknown token "{}"'.format(token)
239
505
  )
240
506
 
241
507
  if total is not None:
@@ -250,9 +516,23 @@ def evaluate_postfix(tokens):
250
516
  return stack.pop()
251
517
 
252
518
 
253
- def tokenize(string, language=None, escape='___'):
519
+ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
254
520
  """
255
- Given a string, return a list of math symbol tokens
521
+ Convert a string into a list of mathematical tokens for processing.
522
+
523
+ Args:
524
+ string (str): The input string containing a mathematical expression.
525
+
526
+ language (str, optional): ISO 639-2 language code for word-based
527
+ parsing. If None, only numeric expressions
528
+ are supported.
529
+
530
+ escape (str, optional): A string used to temporarily replace spaces
531
+ in multi-word phrases during tokenization.
532
+ Default is '___'.
533
+
534
+ Returns:
535
+ list: A list of tokens extracted from the input string.
256
536
  """
257
537
  # Set all words to lowercase
258
538
  string = string.lower()
@@ -262,6 +542,31 @@ def tokenize(string, language=None, escape='___'):
262
542
  character = string[-1]
263
543
  string = string[:-1] + ' ' + character
264
544
 
545
+ # If language is specified, normalize compound operators by removing
546
+ # spaces between their characters. This handles cases like '乘 以'
547
+ # which should be treated as the single compound operator '乘以'.
548
+ # Process by length (longest first) to avoid partial matches.
549
+ if language:
550
+ words = mathwords.words_for_language(language)
551
+
552
+ # Sort all phrases by length (longest first) to handle cases where
553
+ # a shorter phrase is a substring of a longer one
554
+ phrases_by_length = sorted(words, key=len, reverse=True)
555
+
556
+ for phrase in phrases_by_length:
557
+ # For multi-character phrases, create a spaced version
558
+ # and replace it with the non-spaced version
559
+ if len(phrase) > 1:
560
+ # Create pattern with optional spaces between each character
561
+ # For example, '乘以' could appear as '乘 以' or '乘 以'
562
+ spaced_phrase = ' '.join(phrase)
563
+ # Replace spaced version with non-spaced version
564
+ string = string.replace(spaced_phrase, phrase)
565
+
566
+ # Binary operators must have space around them to be tokenized properly
567
+ for operator in mathwords.BINARY_OPERATORS:
568
+ string = string.replace(operator, f' {operator} ')
569
+
265
570
  # Parenthesis must have space around them to be tokenized properly
266
571
  string = string.replace('(', ' ( ')
267
572
  string = string.replace(')', ' ) ')
@@ -281,23 +586,118 @@ def tokenize(string, language=None, escape='___'):
281
586
  return tokens
282
587
 
283
588
 
284
- def parse(string, language=None):
589
+ def parse(
590
+ string: str, language: str = None, stopwords: set[str] = None
591
+ ) -> Union[int, float, str, Decimal]:
285
592
  """
286
- Return a solution to the equation in the input string.
593
+ Parse and evaluate a mathematical expression from a string.
594
+
595
+ This is the main entry point for mathparse. It can handle both numeric
596
+ expressions (like "2 + 3 * 4") and word-based expressions in various
597
+ languages (like "five plus three" in English).
598
+
599
+ Args:
600
+ string (str): The mathematical expression to parse and evaluate.
601
+ Can contain numbers, operators, parentheses, constants,
602
+ and functions. For word-based parsing, must use terms
603
+ from the specified language.
604
+ language (str, optional): ISO 639-2 language code for word-based
605
+ parsing. Supported codes: 'ENG', 'FRE', 'GER',
606
+ 'GRE', 'ITA', 'MAR', 'RUS', 'POR'. If None,
607
+ only numeric expressions are supported.
608
+ stopwords (set[str], optional): A set of words to ignore during
609
+ parsing. This can be used to filter out
610
+ non-mathematical words in expressions.
611
+
612
+ Returns:
613
+ int, float, or str: The result of the mathematical expression.
614
+ Returns 'undefined' for division by zero.
615
+ For division operations, returns a Decimal object
616
+ to maintain precision.
617
+
618
+ Raises:
619
+ InvalidLanguageCodeException:
620
+ An unsupported language code was provided.
621
+ PostfixTokenEvaluationException:
622
+ The expression cannot be evaluated.
623
+
624
+ Examples:
625
+ >>> parse('2 + 3 * 4')
626
+ 14
627
+
628
+ >>> parse('five plus three', language='ENG')
629
+ 8
630
+
631
+ >>> parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
632
+ 24
633
+
634
+ >>> parse('sqrt 16')
635
+ 4.0
636
+
637
+ >>> parse('pi * 2')
638
+ 6.283386
639
+
640
+ >>> parse('10 / 0')
641
+ 'undefined'
642
+
643
+ Note:
644
+ - Follows standard order of operations (PEMDAS)
645
+ - Supports mathematical constants: pi, e
646
+ - Supports unary functions: sqrt, log
647
+ - Each expression must use terms from a single language
648
+ - Division by zero returns 'undefined' instead of raising an exception
287
649
  """
288
650
  if language:
289
- string = replace_word_tokens(string, language)
651
+ if language == 'CHI':
652
+ string = replace_word_tokens_simplified_chinese(
653
+ string, stopwords
654
+ )
655
+ else:
656
+ string = replace_word_tokens(string, language, stopwords)
290
657
 
291
- tokens = tokenize(string)
658
+ tokens = tokenize(string, language)
659
+ tokens = preprocess_unary_operators(tokens)
292
660
  postfix = to_postfix(tokens)
293
661
 
294
662
  return evaluate_postfix(postfix)
295
663
 
296
664
 
297
- def extract_expression(dirty_string, language):
665
+ def extract_expression(dirty_string: str, language: str) -> str:
298
666
  """
299
- Give a string such as: "What is 4 + 4?"
300
- Return the string "4 + 4"
667
+ Extract a mathematical expression from a sentence containing extra text.
668
+
669
+ This function identifies and extracts the mathematical portion from
670
+ natural language sentences like:
671
+ "What is 4 + 4?" or "Calculate five plus three".
672
+ It works by finding the longest sequence of mathematical symbols and words.
673
+
674
+ Args:
675
+ dirty_string (str): A sentence or phrase containing a mathematical
676
+ expression mixed with other text.
677
+ language (str): ISO 639-2 language code to identify mathematical
678
+ words in the target language.
679
+
680
+ Returns:
681
+ str: The extracted mathematical expression as a string.
682
+
683
+ Examples:
684
+ >>> extract_expression("What is 5 plus 3?", language='ENG')
685
+ '5 plus 3'
686
+
687
+ >>> extract_expression(
688
+ "Please calculate two times seven", language='ENG'
689
+ )
690
+ 'two times seven'
691
+
692
+ >>> extract_expression(
693
+ "The result of 10 / 2 should be 5", language=None
694
+ )
695
+ '10 / 2'
696
+
697
+ Note:
698
+ - The function looks for continuous sequences of mathematical terms
699
+ - Non-mathematical words at the beginning and end are stripped
700
+ - The language parameter is required to identify word-based math terms
301
701
  """
302
702
  tokens = tokenize(dirty_string, language)
303
703
 
mathparse/mathwords.py CHANGED
@@ -1,21 +1,76 @@
1
- # -*- coding: utf-8 -*-
2
- from __future__ import unicode_literals
3
- import math
4
-
5
1
  """
6
2
  Utility methods for getting math word terms.
7
3
  """
4
+ import math
8
5
 
9
6
  BINARY_OPERATORS = {
10
7
  '^', '*', '/', '+', '-'
11
8
  }
12
9
 
13
10
  MATH_WORDS = {
11
+ 'DUT': {
12
+ 'prefix_unary_operators': {
13
+ 'vierkantswortel van': 'sqrt',
14
+ 'wortel van': 'sqrt'
15
+ },
16
+ 'postfix_unary_operators': {
17
+ 'kwadraat': '^ 2'
18
+ },
19
+ 'binary_operators': {
20
+ 'plus': '+',
21
+ 'gedeeld door': '/',
22
+ 'min': '-',
23
+ 'maal': '*',
24
+ 'tot de macht': '^',
25
+ 'tot de': '^'
26
+ },
27
+ 'numbers': {
28
+ 'nul': 0,
29
+ 'een': 1,
30
+ 'één': 1,
31
+ 'twee': 2,
32
+ 'drie': 3,
33
+ 'vier': 4,
34
+ 'vijf': 5,
35
+ 'zes': 6,
36
+ 'zeven': 7,
37
+ 'acht': 8,
38
+ 'negen': 9,
39
+ 'tien': 10,
40
+ 'elf': 11,
41
+ 'twaalf': 12,
42
+ 'dertien': 13,
43
+ 'veertien': 14,
44
+ 'vijftien': 15,
45
+ 'zestien': 16,
46
+ 'zeventien': 17,
47
+ 'achttien': 18,
48
+ 'negentien': 19,
49
+ 'twintig': 20,
50
+ 'dertig': 30,
51
+ 'veertig': 40,
52
+ 'vijftig': 50,
53
+ 'zestig': 60,
54
+ 'zeventig': 70,
55
+ 'tachtig': 80,
56
+ 'negentig': 90
57
+ },
58
+ 'scales': {
59
+ 'honderd': 100,
60
+ 'duizend': 1000,
61
+ 'miljoen': 1000000,
62
+ 'miljard': 1000000000,
63
+ 'biljard': 1000000000000
64
+ }
65
+ },
14
66
  'ENG': {
15
- 'unary_operators': {
67
+ 'prefix_unary_operators': {
68
+ 'square root of': 'sqrt',
69
+ 'negative': 'neg'
70
+ },
71
+ 'postfix_unary_operators': {
16
72
  'squared': '^ 2',
17
73
  'cubed': '^ 3',
18
- 'square root of': 'sqrt'
19
74
  },
20
75
  'binary_operators': {
21
76
  'plus': '+',
@@ -63,6 +118,13 @@ MATH_WORDS = {
63
118
  }
64
119
  },
65
120
  'FRE': {
121
+ 'prefix_unary_operators': {
122
+ 'racine carrée de': 'sqrt'
123
+ },
124
+ 'postfix_unary_operators': {
125
+ 'au carré': '^ 2',
126
+ 'au cube': '^ 3'
127
+ },
66
128
  'binary_operators': {
67
129
  'plus': '+',
68
130
  'divisé par': '/',
@@ -73,6 +135,7 @@ MATH_WORDS = {
73
135
  'à la puissance': '^'
74
136
  },
75
137
  'numbers': {
138
+ 'zéro': 0,
76
139
  'un': 1,
77
140
  'deux': 2,
78
141
  'trois': 3,
@@ -113,6 +176,14 @@ MATH_WORDS = {
113
176
  }
114
177
  },
115
178
  'GER': {
179
+ 'prefix_unary_operators': {
180
+ 'Quadratwurzel von': 'sqrt',
181
+ 'Wurzel von': 'sqrt'
182
+ },
183
+ 'postfix_unary_operators': {
184
+ 'quadriert': '^ 2',
185
+ 'hoch drei': '^ 3'
186
+ },
116
187
  'binary_operators': {
117
188
  'plus': '+',
118
189
  'geteilt durch': '/',
@@ -122,11 +193,11 @@ MATH_WORDS = {
122
193
  'multipliziert mit': '*',
123
194
  'im Quadrat': '^ 2',
124
195
  'hoch zwei': '^ 2',
125
- 'quadriert': '^ 2',
126
196
  'cubed': '^ 3',
127
197
  'hoch': '^'
128
198
  },
129
199
  'numbers': {
200
+ 'null': 0,
130
201
  'eins': 1,
131
202
  'zwei': 2,
132
203
  'drei': 3,
@@ -165,10 +236,12 @@ MATH_WORDS = {
165
236
  }
166
237
  },
167
238
  'GRE': {
168
- 'unary_operators': {
239
+ 'prefix_unary_operators': {
240
+ 'τετραγωνική ρίζα του': 'sqrt'
241
+ },
242
+ 'postfix_unary_operators': {
169
243
  'στο τετράγωνο': '^ 2',
170
244
  'στον κύβο': '^ 3',
171
- 'τετραγωνική ρίζα του': 'sqrt'
172
245
  },
173
246
  'binary_operators': {
174
247
  'συν': '+', 'και': '+',
@@ -219,6 +292,13 @@ MATH_WORDS = {
219
292
  }
220
293
  },
221
294
  'ITA': {
295
+ 'prefix_unary_operators': {
296
+ 'radice quadrata di': 'sqrt'
297
+ },
298
+ 'postfix_unary_operators': {
299
+ 'al quadrato': '^ 2',
300
+ 'al cubo': '^ 3'
301
+ },
222
302
  'binary_operators': {
223
303
  'più': '+',
224
304
  'diviso': '/',
@@ -229,6 +309,7 @@ MATH_WORDS = {
229
309
  'alla potenza di': '^'
230
310
  },
231
311
  'numbers': {
312
+ 'zero': 0,
232
313
  'uno': 1,
233
314
  'due': 2,
234
315
  'tre': 3,
@@ -266,6 +347,13 @@ MATH_WORDS = {
266
347
  }
267
348
  },
268
349
  'MAR': {
350
+ 'prefix_unary_operators': {
351
+ 'वर्गमूल': 'sqrt'
352
+ },
353
+ 'postfix_unary_operators': {
354
+ 'वर्ग': '^ 2',
355
+ 'घन': '^ 3'
356
+ },
269
357
  'binary_operators': {
270
358
  'बेरीज': '+',
271
359
  'भागाकार': '/',
@@ -315,6 +403,14 @@ MATH_WORDS = {
315
403
  }
316
404
  },
317
405
  'RUS': {
406
+ 'prefix_unary_operators': {
407
+ 'квадратный корень из': 'sqrt',
408
+ 'корень из': 'sqrt'
409
+ },
410
+ 'postfix_unary_operators': {
411
+ 'в квадрате': '^ 2',
412
+ 'в кубе': '^ 3'
413
+ },
318
414
  'binary_operators': {
319
415
  'плюс': '+',
320
416
  'разделить': '/',
@@ -332,6 +428,7 @@ MATH_WORDS = {
332
428
  'степень': '^'
333
429
  },
334
430
  'numbers': {
431
+ 'ноль': 0,
335
432
  'один': 1,
336
433
  'два': 2,
337
434
  'три': 3,
@@ -369,10 +466,12 @@ MATH_WORDS = {
369
466
  }
370
467
  },
371
468
  'POR': {
372
- 'unary_operators': {
469
+ 'prefix_unary_operators': {
470
+ 'raiz quadrada de': 'sqrt'
471
+ },
472
+ 'postfix_unary_operators': {
373
473
  'ao quadrado': '^ 2',
374
474
  'ao cubo': '^ 3',
375
- 'raiz quadrada de': 'sqrt'
376
475
  },
377
476
  'binary_operators': {
378
477
  'mais': '+',
@@ -419,6 +518,265 @@ MATH_WORDS = {
419
518
  'bilhão': 1000000000,
420
519
  'trilhão': 1000000000000
421
520
  }
521
+ },
522
+ 'UKR': {
523
+ 'prefix_unary_operators': {
524
+ 'квадратний корінь з': 'sqrt',
525
+ 'корінь з': 'sqrt'
526
+ },
527
+ 'postfix_unary_operators': {
528
+ 'у квадраті': '^ 2',
529
+ 'у кубі': '^ 3'
530
+ },
531
+ 'binary_operators': {
532
+ 'додати': '+',
533
+ 'розділити': '/',
534
+ 'поділити на': '/',
535
+ 'ділити на': '/',
536
+ 'мінус': '-',
537
+ 'відняти': '-',
538
+ 'відняти від': '-',
539
+ 'помножити': '*',
540
+ 'помножене на': '*',
541
+ 'помножити на': '*',
542
+ 'квадрат': '^ 2',
543
+ 'у квадраті': '^ 2',
544
+ 'зведений у куб': '^ 3',
545
+ 'ступінь': '^'
546
+ },
547
+ 'numbers': {
548
+ 'нуль': 0,
549
+ 'один': 1,
550
+ 'два': 2,
551
+ 'три': 3,
552
+ 'чотири': 4,
553
+ 'п’ять': 5,
554
+ 'шість': 6,
555
+ 'сім': 7,
556
+ 'вісім': 8,
557
+ 'дев’ять': 9,
558
+ 'десять': 10,
559
+ 'одинадцять': 11,
560
+ 'дванадцять': 12,
561
+ 'тринадцять': 13,
562
+ 'чотирнадцять': 14,
563
+ 'п’ятнадцять': 15,
564
+ 'шістнадцять': 16,
565
+ 'сімнадцять': 17,
566
+ 'вісімнадцять': 18,
567
+ 'дев’ятнадцять': 19,
568
+ 'двадцять': 20,
569
+ 'тридцять': 30,
570
+ 'сорок': 40,
571
+ 'п’ятдесят': 50,
572
+ 'шістдесят': 60,
573
+ 'сімдесят': 70,
574
+ 'вісімдесят': 80,
575
+ 'дев’яносто': 90
576
+ },
577
+ 'scales': {
578
+ 'сто': 100,
579
+ 'тисяча': 1000,
580
+ 'мільйон': 1000000,
581
+ 'мільярд': 1000000000,
582
+ 'трильйон': 1000000000000
583
+ }
584
+ },
585
+ 'ESP': {
586
+ 'prefix_unary_operators': {
587
+ 'raiz cuadrada de': 'sqrt'
588
+ },
589
+ 'postfix_unary_operators': {
590
+ 'al cuadrado': '^ 2',
591
+ 'al cubo': '^ 3',
592
+ },
593
+ 'binary_operators': {
594
+ 'más': '+',
595
+ 'entre': '/',
596
+ 'menos': '-',
597
+ 'por': '*',
598
+ 'veces': '*',
599
+ 'elevado al': '^'
600
+ },
601
+ 'numbers': {
602
+ 'cero': 0,
603
+ 'uno': 1,
604
+ 'dos': 2,
605
+ 'tres': 3,
606
+ 'cuatro': 4,
607
+ 'cinco': 5,
608
+ 'seis': 6,
609
+ 'siete': 7,
610
+ 'ocho': 8,
611
+ 'nueve': 9,
612
+ 'diez': 10,
613
+ 'once': 11,
614
+ 'doce': 12,
615
+ 'trece': 13,
616
+ 'catorce': 14,
617
+ 'quince': 15,
618
+ 'dieciséis': 16,
619
+ 'diecisiete': 17,
620
+ 'dieciocho': 18,
621
+ 'diecinueve': 19,
622
+ 'veinte': 20,
623
+ 'treinta': 30,
624
+ 'cuarenta': 40,
625
+ 'cincuenta': 50,
626
+ 'sesenta': 60,
627
+ 'setenta': 70,
628
+ 'ochenta': 80,
629
+ 'noventa': 90
630
+ },
631
+ 'scales': {
632
+ 'cien': 100,
633
+ 'mil': 1000,
634
+ 'millon': 1000000,
635
+ 'billon': 1000000000,
636
+ 'trillon': 1000000000000
637
+ }
638
+ },
639
+ 'THA': {
640
+ 'prefix_unary_operators': {
641
+ 'สแควรูท': 'sqrt'
642
+ },
643
+ 'postfix_unary_operators': {
644
+ 'ยกกำลังสอง': '^ 2',
645
+ 'ยกกำลังสาม': '^ 3'
646
+ },
647
+ 'binary_operators': {
648
+ 'บวก': '+',
649
+ 'หาร': '/',
650
+ 'ลบ': '-',
651
+ 'คูณ': '*',
652
+ 'ยกกำลัง': '^'
653
+ },
654
+ 'numbers': {
655
+ 'ศูนย์': 0,
656
+ 'หนึ่ง': 1,
657
+ 'สอง': 2,
658
+ 'สาม': 3,
659
+ 'สี่': 4,
660
+ 'ห้า': 5,
661
+ 'หก': 6,
662
+ 'เจ็ด': 7,
663
+ 'แปด': 8,
664
+ 'เก้า': 9,
665
+ 'สิบ': 10,
666
+ 'สิบเอ็ด': 11,
667
+ 'สิบสอง': 12,
668
+ 'สิบสาม': 13,
669
+ 'สิบสี่': 14,
670
+ 'สิบห้า': 15,
671
+ 'สิบหก': 16,
672
+ 'สิบเจ็ด': 17,
673
+ 'สิบแปด': 18,
674
+ 'สิบเก้า': 19,
675
+ 'ยี่สิบ': 20,
676
+ 'สามสิบ': 30,
677
+ 'สี่สิบ': 40,
678
+ 'ห้าสิบ': 50,
679
+ 'หกสิบ': 60,
680
+ 'เจ็ดสิบ': 70,
681
+ 'แปดสิบ': 80,
682
+ 'เก้าสิบ': 90
683
+ },
684
+ 'scales': {
685
+ 'ร้อย': 100,
686
+ 'พัน': 1000,
687
+ 'หมื่น': 10000,
688
+ 'แสน': 100000,
689
+ 'ล้าน': 1000000,
690
+ 'พันล้าน': 1000000000,
691
+ 'ล้านล้าน': 1000000000000
692
+ }
693
+ },
694
+ 'CHI': {
695
+ 'prefix_unary_operators': {
696
+ '平方根': 'sqrt',
697
+ '开方': 'sqrt',
698
+ '负': 'neg'
699
+ },
700
+ 'postfix_unary_operators': {
701
+ '平方': '^ 2',
702
+ '立方': '^ 3',
703
+ '的平方': '^ 2',
704
+ '的立方': '^ 3'
705
+ },
706
+ 'binary_operators': {
707
+ '加': '+',
708
+ '加上': '+',
709
+ '加法': '+',
710
+ '除以': '/',
711
+ '除': '/',
712
+ '除法': '/',
713
+ '减': '-',
714
+ '减去': '-',
715
+ '减法': '-',
716
+ '乘': '*',
717
+ '乘以': '*',
718
+ '乘法': '*',
719
+ '乘上': '*',
720
+ '倍': '*',
721
+ '的': '^',
722
+ '次方': '^',
723
+ '次幂': '^'
724
+ },
725
+ 'numbers': {
726
+ '零': 0,
727
+ '一': 1,
728
+ '二': 2,
729
+ '三': 3,
730
+ '四': 4,
731
+ '五': 5,
732
+ '六': 6,
733
+ '七': 7,
734
+ '八': 8,
735
+ '九': 9,
736
+ '十': 10,
737
+ '十一': 11,
738
+ '十二': 12,
739
+ '十三': 13,
740
+ '十四': 14,
741
+ '十五': 15,
742
+ '十六': 16,
743
+ '十七': 17,
744
+ '十八': 18,
745
+ '十九': 19,
746
+ '二十': 20,
747
+ '三十': 30,
748
+ '四十': 40,
749
+ '五十': 50,
750
+ '六十': 60,
751
+ '七十': 70,
752
+ '八十': 80,
753
+ '九十': 90,
754
+ '壹': 1,
755
+ '贰': 2,
756
+ '两': 2,
757
+ '叁': 3,
758
+ '肆': 4,
759
+ '伍': 5,
760
+ '陆': 6,
761
+ '柒': 7,
762
+ '捌': 8,
763
+ '玖': 9,
764
+ '拾': 10
765
+ },
766
+ 'scales': {
767
+ '十': 10,
768
+ '百': 100,
769
+ '千': 1000,
770
+ '万': 10000,
771
+ '十万': 100000,
772
+ '百万': 1000000,
773
+ '千万': 10000000,
774
+ '亿': 100000000,
775
+ '十亿': 1000000000,
776
+ '百亿': 10000000000,
777
+ '千亿': 100000000000,
778
+ '万亿': 1000000000000
779
+ }
422
780
  }
423
781
  }
424
782
 
@@ -436,19 +794,23 @@ UNARY_FUNCTIONS = {
436
794
  'sqrt': math.sqrt,
437
795
 
438
796
  # Most people assume a log of base 10 when a base is not specified
439
- 'log': math.log10
797
+ 'log': math.log10,
798
+
799
+ # Unary minus function for negative numbers
800
+ 'neg': lambda x: -x
440
801
  }
441
802
 
442
803
 
443
804
  class InvalidLanguageCodeException(Exception):
444
805
  """
445
- Exception to be raised when a language code is given that
446
- is not a part of the ISO 639-2 standard.
806
+ Exception to be raised when a language code is specified that is not a part
807
+ of the ISO 639-2 standard, or if the specified language is not yet
808
+ supported by mathparse.
447
809
  """
448
810
  pass
449
811
 
450
812
 
451
- def word_groups_for_language(language_code):
813
+ def word_groups_for_language(language_code: str) -> dict[str, dict[str, str]]:
452
814
  """
453
815
  Return the math word groups for a language code.
454
816
  The language_code should be an ISO 639-2 language code.
@@ -462,16 +824,16 @@ def word_groups_for_language(language_code):
462
824
  return MATH_WORDS[language_code]
463
825
 
464
826
 
465
- def words_for_language(language_code):
827
+ def words_for_language(language_code: str) -> set[str]:
466
828
  """
467
829
  Return the math words for a language code.
468
830
  The language_code should be an ISO 639-2 language code.
469
831
  https://www.loc.gov/standards/iso639-2/php/code_list.php
470
832
  """
471
833
  word_groups = word_groups_for_language(language_code)
472
- words = []
834
+ words = set()
473
835
 
474
836
  for group in word_groups:
475
- words.extend(word_groups[group].keys())
837
+ words.update(word_groups[group].keys())
476
838
 
477
839
  return words
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathparse
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: mathparse is a library for solving mathematical equations contained in strings
5
5
  Author: Gunther Cox
6
6
  License-Expression: MIT
@@ -36,24 +36,34 @@ from mathparse import mathparse
36
36
  mathparse.parse('50 * (85 / 100)')
37
37
  >>> 42.5
38
38
 
39
- mathparse.parse('one hundred times fifty four', mathparse.codes.ENG)
39
+ mathparse.parse('one hundred times fifty four', language='ENG')
40
40
  >>> 5400
41
41
 
42
42
  mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
43
43
  >>> 24
44
44
  ```
45
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
+
46
57
  ## Installation
47
58
 
48
59
  ```bash
49
60
  pip install mathparse
50
61
  ```
51
62
 
52
- ## Language support
63
+ ## Documentation
53
64
 
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.
65
+ See the full documentation at https://mathparse.chatterbot.us
56
66
 
57
- ## History
67
+ ## Changelog
58
68
 
59
- See [release notes](https://github.com/gunthercox/ChatterBot/releases) for changes.
69
+ See [release notes](https://github.com/gunthercox/mathparse/releases) for changes.
@@ -0,0 +1,8 @@
1
+ mathparse/__init__.py,sha256=ALL73dYTKpEfBaZKrAYR148e8QXbrlFYlYDgjF8ePoY,110
2
+ mathparse/mathparse.py,sha256=Qt2hP6IkPtPpZRlH5fMiS9zKEnoR2TETRcNd3lm8e-c,24122
3
+ mathparse/mathwords.py,sha256=JRzDXPVM7K8VMjzolIpNUGU7AtLiT7WLRsfo6KDT_OU,23516
4
+ mathparse-0.2.3.dist-info/licenses/LICENSE,sha256=_buf4D_BxjT3x8SBhP0Rh966qP3zpbButcLI4bPq_TY,1068
5
+ mathparse-0.2.3.dist-info/METADATA,sha256=i8hRxYIn38xsDhHdmW6ih35AZ5yzfDMoQCs7Iz3VIGc,2325
6
+ mathparse-0.2.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ mathparse-0.2.3.dist-info/top_level.txt,sha256=rAQj3bfKyZhbFL6WxVLRCqnvwQPI2ZCc_FNrwx6Hlmc,10
8
+ mathparse-0.2.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (78.1.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,8 +0,0 @@
1
- mathparse/__init__.py,sha256=_3iITTMVoA5v1mEbRKsLcAFU2BtH2sV9SPTkfbpU-xs,110
2
- mathparse/mathparse.py,sha256=_tmr746_Ofx1_CWfoKOlKc4phBNHLtiR_w-JhVbnexo,8242
3
- mathparse/mathwords.py,sha256=p7wMTdSUk3DiQ8SgW8U2AOMjVHXyqMKGNNKKxzWlr4o,13231
4
- mathparse-0.2.1.dist-info/licenses/LICENSE,sha256=_buf4D_BxjT3x8SBhP0Rh966qP3zpbButcLI4bPq_TY,1068
5
- mathparse-0.2.1.dist-info/METADATA,sha256=xWgOv4h29tHeOpUxh1YeLzyKRUIh7ENn2mJJIv5sPKI,1838
6
- mathparse-0.2.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
7
- mathparse-0.2.1.dist-info/top_level.txt,sha256=rAQj3bfKyZhbFL6WxVLRCqnvwQPI2ZCc_FNrwx6Hlmc,10
8
- mathparse-0.2.1.dist-info/RECORD,,