mathparse 0.2.2__tar.gz → 0.2.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathparse
3
- Version: 0.2.2
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
@@ -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.2'
5
+ __version__ = '0.2.3'
@@ -98,6 +98,115 @@ def find_word_groups(string: str, words: list) -> list:
98
98
  return result
99
99
 
100
100
 
101
+ def replace_word_tokens_simplified_chinese(
102
+ string, stopwords: set[str] = None
103
+ ) -> str:
104
+ """
105
+ simplified Chinese version:
106
+ Given a string and an ISO 639-2 language code,
107
+ return the string with the words replaced with
108
+ an operational equivalent.
109
+ """
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
+
101
210
  def replace_word_tokens(
102
211
  string: str, language: str, stopwords: set[str] = None
103
212
  ) -> str:
@@ -107,19 +216,39 @@ def replace_word_tokens(
107
216
  Given a string and an ISO 639-2 language code,
108
217
  return the string with the words replaced with
109
218
  an operational equivalent.
219
+
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.
110
233
  """
111
234
  words = mathwords.word_groups_for_language(language)
112
235
 
113
- # Replace binary operator words with numeric operators
236
+ # Process operators by length (longest first) to handle compound operators
114
237
  binary_operators = words['binary_operators']
115
- for operator in frozenset(binary_operators.keys()):
238
+ sorted_operators = sorted(binary_operators.keys(), key=len, reverse=True)
239
+ for operator in sorted_operators:
116
240
  if operator in string:
117
241
  string = string.replace(operator, binary_operators[operator])
118
242
 
119
243
  # Handle prefix unary operators (like "square root of")
120
244
  if 'prefix_unary_operators' in words:
121
245
  prefix_unary_operators = words['prefix_unary_operators']
122
- for operator in frozenset(prefix_unary_operators.keys()):
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:
123
252
  if operator in string:
124
253
  string = string.replace(
125
254
  operator, prefix_unary_operators[operator]
@@ -128,7 +257,12 @@ def replace_word_tokens(
128
257
  # Handle postfix unary operators (like "squared", "cubed")
129
258
  if 'postfix_unary_operators' in words:
130
259
  postfix_unary_operators = words['postfix_unary_operators']
131
- for operator in frozenset(postfix_unary_operators.keys()):
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:
132
266
  if operator in string:
133
267
  # Captures the number/operand before the unary operator
134
268
  pattern = r'(\w+)\s+' + re.escape(operator)
@@ -185,8 +319,7 @@ def replace_word_tokens(
185
319
 
186
320
  # Replace scaling multipliers with numeric values
187
321
  scales = words['scales']
188
- end_index_characters = mathwords.BINARY_OPERATORS
189
- end_index_characters.add('(')
322
+ end_index_characters = mathwords.BINARY_OPERATORS | {'('}
190
323
 
191
324
  word_matches = find_word_groups(string, frozenset(scales.keys()))
192
325
 
@@ -223,6 +356,48 @@ def replace_word_tokens(
223
356
  return string
224
357
 
225
358
 
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
+
226
401
  def to_postfix(tokens: list) -> list:
227
402
  """
228
403
  Convert a list of evaluatable tokens to postfix format.
@@ -367,6 +542,31 @@ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
367
542
  character = string[-1]
368
543
  string = string[:-1] + ' ' + character
369
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
+
370
570
  # Parenthesis must have space around them to be tokenized properly
371
571
  string = string.replace('(', ' ( ')
372
572
  string = string.replace(')', ' ) ')
@@ -448,9 +648,15 @@ def parse(
448
648
  - Division by zero returns 'undefined' instead of raising an exception
449
649
  """
450
650
  if language:
451
- string = replace_word_tokens(string, language, stopwords)
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)
452
657
 
453
- tokens = tokenize(string)
658
+ tokens = tokenize(string, language)
659
+ tokens = preprocess_unary_operators(tokens)
454
660
  postfix = to_postfix(tokens)
455
661
 
456
662
  return evaluate_postfix(postfix)
@@ -1,17 +1,72 @@
1
- import math
2
-
3
1
  """
4
2
  Utility methods for getting math word terms.
5
3
  """
4
+ import math
6
5
 
7
6
  BINARY_OPERATORS = {
8
7
  '^', '*', '/', '+', '-'
9
8
  }
10
9
 
11
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
+ },
12
66
  'ENG': {
13
67
  'prefix_unary_operators': {
14
- 'square root of': 'sqrt'
68
+ 'square root of': 'sqrt',
69
+ 'negative': 'neg'
15
70
  },
16
71
  'postfix_unary_operators': {
17
72
  'squared': '^ 2',
@@ -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,
@@ -221,6 +292,13 @@ MATH_WORDS = {
221
292
  }
222
293
  },
223
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
+ },
224
302
  'binary_operators': {
225
303
  'più': '+',
226
304
  'diviso': '/',
@@ -231,6 +309,7 @@ MATH_WORDS = {
231
309
  'alla potenza di': '^'
232
310
  },
233
311
  'numbers': {
312
+ 'zero': 0,
234
313
  'uno': 1,
235
314
  'due': 2,
236
315
  'tre': 3,
@@ -268,6 +347,13 @@ MATH_WORDS = {
268
347
  }
269
348
  },
270
349
  'MAR': {
350
+ 'prefix_unary_operators': {
351
+ 'वर्गमूल': 'sqrt'
352
+ },
353
+ 'postfix_unary_operators': {
354
+ 'वर्ग': '^ 2',
355
+ 'घन': '^ 3'
356
+ },
271
357
  'binary_operators': {
272
358
  'बेरीज': '+',
273
359
  'भागाकार': '/',
@@ -317,6 +403,14 @@ MATH_WORDS = {
317
403
  }
318
404
  },
319
405
  'RUS': {
406
+ 'prefix_unary_operators': {
407
+ 'квадратный корень из': 'sqrt',
408
+ 'корень из': 'sqrt'
409
+ },
410
+ 'postfix_unary_operators': {
411
+ 'в квадрате': '^ 2',
412
+ 'в кубе': '^ 3'
413
+ },
320
414
  'binary_operators': {
321
415
  'плюс': '+',
322
416
  'разделить': '/',
@@ -334,6 +428,7 @@ MATH_WORDS = {
334
428
  'степень': '^'
335
429
  },
336
430
  'numbers': {
431
+ 'ноль': 0,
337
432
  'один': 1,
338
433
  'два': 2,
339
434
  'три': 3,
@@ -423,6 +518,265 @@ MATH_WORDS = {
423
518
  'bilhão': 1000000000,
424
519
  'trilhão': 1000000000000
425
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
+ }
426
780
  }
427
781
  }
428
782
 
@@ -440,7 +794,10 @@ UNARY_FUNCTIONS = {
440
794
  'sqrt': math.sqrt,
441
795
 
442
796
  # Most people assume a log of base 10 when a base is not specified
443
- 'log': math.log10
797
+ 'log': math.log10,
798
+
799
+ # Unary minus function for negative numbers
800
+ 'neg': lambda x: -x
444
801
  }
445
802
 
446
803
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathparse
3
- Version: 0.2.2
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
@@ -13,5 +13,6 @@ tests/test_binary_operations.py
13
13
  tests/test_complex_statements.py
14
14
  tests/test_language_support.py
15
15
  tests/test_replace_word_tokens.py
16
+ tests/test_simplified_chinese.py
16
17
  tests/test_unary_operations.py
17
18
  tests/test_utils.py
@@ -74,6 +74,21 @@ class PositiveIntegerTestCase(TestCase):
74
74
 
75
75
  self.assertEqual(str(result), '12.04')
76
76
 
77
+ def test_operation_precedence(self):
78
+ result = mathparse.parse('2 + 3 * (4 - 2) ^ 2 / 2')
79
+
80
+ self.assertEqual(result, 8)
81
+
82
+ def test_tokens_with_extra_spaces(self):
83
+ result = mathparse.parse(' 2 + 3 * ( 4 - 2 ) ^ 2 / 2 ')
84
+
85
+ self.assertEqual(result, 8)
86
+
87
+ def test_tokens_with_no_spaces(self):
88
+ result = mathparse.parse('2+3*(4-2)^2/2')
89
+
90
+ self.assertEqual(result, 8)
91
+
77
92
 
78
93
  class PositiveFloatTestCase(TestCase):
79
94
 
@@ -96,3 +111,11 @@ class PositiveFloatTestCase(TestCase):
96
111
  result = mathparse.parse('0.6 / 0.2')
97
112
 
98
113
  self.assertEqual(result, 3)
114
+
115
+
116
+ class WordOperatorTestCase(TestCase):
117
+
118
+ def test_power_of(self):
119
+ result = mathparse.parse('2 to the power of 3', language='ENG')
120
+
121
+ self.assertEqual(result, 8)
@@ -52,3 +52,15 @@ class ComplexStatementsTestCase(TestCase):
52
52
  str(e.exception),
53
53
  'Unsupported mathematical term: "squiggle"'
54
54
  )
55
+
56
+ def test_stopwords_contained_within_expressions(self):
57
+ """
58
+ Stopwords should not be removed if they are a part of a valid
59
+ mathematical expression.
60
+ """
61
+ result = mathparse.parse(
62
+ 'the square root of four',
63
+ language='ENG',
64
+ stopwords={'the', 'of'}
65
+ )
66
+ self.assertEqual(result, 2)
@@ -16,19 +16,19 @@ class LanguageSupportTestCase(TestCase):
16
16
 
17
17
  def test_parsing_with_unsupported_operator(self):
18
18
  """
19
- NOTE: The French language currently is missing support for
20
- unary_operators. This test will start failing when those are
21
- added to the language support.
19
+ Simulate parsing a string with an unsupported operator in a supported
20
+ language. Eg. using "invalid" to represent an unsupported unary
21
+ operator in French.
22
22
  """
23
23
  with self.assertRaises(mathparse.PostfixTokenEvaluationException) as e:
24
24
  mathparse.parse(
25
- # Three times the square root of 4
26
- 'trois fois la racine carrée de 4',
25
+ # Three times the invalid root of 4
26
+ 'trois fois la invalid carrée de 4',
27
27
  language='FRE',
28
28
  stopwords={'la', 'de'}
29
29
  )
30
30
 
31
31
  self.assertEqual(
32
32
  str(e.exception),
33
- 'Unsupported mathematical term: "racine"'
33
+ 'Unsupported mathematical term: "invalid"'
34
34
  )
@@ -0,0 +1,167 @@
1
+ from unittest import TestCase
2
+ from mathparse import mathparse
3
+
4
+
5
+ class ChineseTestCase(TestCase):
6
+ """
7
+ Useful examples were noted for Mandarin language support in
8
+ https://github.com/gunthercox/mathparse/issues/19
9
+
10
+ NOTES:
11
+ -2 + 2 in Mandarin statement could be '负二加二'.
12
+ '负' means 'negative', '二' means 2 and '加' means 'plus'. The Mandarin
13
+ language has almost the same grammar/order as English when stating a
14
+ mathematical statement. For the basic four operators:
15
+ plus, minus, multiplication and division, statements in Mandarin are
16
+ always like 'a (positive/negative) number' + 'operator' +
17
+ 'a (positive/negative) number', similar to English.
18
+
19
+ 22 in Mandarin could be '二的平方'.
20
+ '平方' means 'squares', and '的' is a necessary character that could be
21
+ interpreted as 'whose'.
22
+ For exponential statements in Mandarin, there is a general rule:
23
+ 22 —> '二的平方'
24
+ 32 —> '三的平方'
25
+ 42 —> '四的平方'
26
+ Just replace the base number.
27
+ Similarly for exponent of three:
28
+ 2^3 —> '二的立方'
29
+ 3^3 —> '三的立方'
30
+ 4^3 —> '四的立方'
31
+ where '立方' is a specific word for exponent of three.
32
+ But it becomes more regular for the exponent greater or equal to four.
33
+ It would be:
34
+ 2^4 —> '二的四次方' where '四' means 4
35
+ 2^5 —> '三的五次方' where '五' means 5
36
+ 2^10 —> '四的十次方' where '十' means 10
37
+ Basically the rule becomes 'base number's exponent of n'.
38
+ So actually only the exponent of 2 and 3 have their specific
39
+ name ('平方','立方' respectively).
40
+ """
41
+
42
+ def test_addition_with_compound_statement(self):
43
+ """
44
+ 二加二 is "two plus two" but no spaces are used between the characters.
45
+ """
46
+ result = mathparse.parse('二加二', language='CHI')
47
+ self.assertEqual(result, 4)
48
+
49
+ def test_addition(self):
50
+ result = mathparse.parse('四 加 四', language='CHI')
51
+ self.assertEqual(result, 8)
52
+
53
+ def test_addition_with_negative_number(self):
54
+ """
55
+ 负二加二 is "-2 plus 2", no spaces are used between the characters.
56
+ """
57
+ result = mathparse.parse('负二加二', language='CHI')
58
+ self.assertEqual(result, 0)
59
+
60
+ def test_compound_operators(self):
61
+ """
62
+ Test compound operators like 除以, 乘以, 加上
63
+ """
64
+ # Division with compound operator
65
+ result = mathparse.parse('八 除以 二', language='CHI')
66
+ self.assertEqual(result, 4)
67
+
68
+ # Multiplication with compound operator
69
+ result = mathparse.parse('三 乘以 五', language='CHI')
70
+ self.assertEqual(result, 15)
71
+
72
+ # Addition with compound operator
73
+ result = mathparse.parse('十 加上 五', language='CHI')
74
+ self.assertEqual(result, 15)
75
+
76
+ def test_deconstructions(self):
77
+ """
78
+ Test Chinese 的 possessive constructions for powers.
79
+ """
80
+ # Square (specific name)
81
+ result = mathparse.parse('三的平方', language='CHI')
82
+ self.assertEqual(result, 9)
83
+
84
+ # Cube (specific name)
85
+ result = mathparse.parse('二的立方', language='CHI')
86
+ self.assertEqual(result, 8)
87
+
88
+ # General power construction
89
+ result = mathparse.parse('二的四次方', language='CHI')
90
+ self.assertEqual(result, 16)
91
+
92
+ result = mathparse.parse('三的五次方', language='CHI')
93
+ self.assertEqual(result, 243)
94
+
95
+ def test_deconstructions_with_spaces(self):
96
+ """
97
+ Test Chinese 的 constructions with spaces.
98
+ """
99
+ result = mathparse.parse('二 的 四 次方', language='CHI')
100
+ self.assertEqual(result, 16)
101
+
102
+ result = mathparse.parse('三 的平方', language='CHI')
103
+ self.assertEqual(result, 9)
104
+
105
+ def test_prefix_unary_operators(self):
106
+ """Test Chinese prefix operators like square root"""
107
+ result = mathparse.parse('平方根 九', language='CHI')
108
+ self.assertEqual(result, 3.0)
109
+
110
+ result = mathparse.parse('开方 十六', language='CHI')
111
+ self.assertEqual(result, 4.0)
112
+
113
+ def test_postfix_unary_operators(self):
114
+ """Test Chinese postfix operators without 的"""
115
+ result = mathparse.parse('三 平方', language='CHI')
116
+ self.assertEqual(result, 9)
117
+
118
+ result = mathparse.parse('二 立方', language='CHI')
119
+ self.assertEqual(result, 8)
120
+
121
+
122
+ class SimplifiedChineseTestCase(TestCase):
123
+
124
+ def test_addition_words(self):
125
+ result = mathparse.parse('四加四', language='CHI')
126
+
127
+ self.assertEqual(result, 8)
128
+
129
+ def test_addition_words_large(self):
130
+ result = mathparse.parse('四千两百一加五百', language='CHI')
131
+
132
+ self.assertEqual(result, 4701)
133
+
134
+ def test_subtraction_words(self):
135
+ result = mathparse.parse('三十减二十', language='CHI')
136
+
137
+ self.assertEqual(result, 10)
138
+
139
+ def test_multiplication_words(self):
140
+ result = mathparse.parse('九乘九', language='CHI')
141
+
142
+ self.assertEqual(result, 81)
143
+
144
+ def test_division_words(self):
145
+ result = mathparse.parse('十五除以五', language='CHI')
146
+
147
+ self.assertEqual(result, 3)
148
+
149
+ def test_division_words_large(self):
150
+ result = mathparse.parse('一千两百四除以一百', language='CHI')
151
+
152
+ self.assertEqual(str(result), '12.04')
153
+
154
+ def test_sqrt(self):
155
+ result = mathparse.parse('四开方', language='CHI')
156
+
157
+ self.assertEqual(result, 2)
158
+
159
+ def test_squared(self):
160
+ result = mathparse.parse('二平方', language='CHI')
161
+
162
+ self.assertEqual(result, 4)
163
+
164
+ def test_cubed(self):
165
+ result = mathparse.parse('二立方', language='CHI')
166
+
167
+ self.assertEqual(result, 8)
@@ -36,3 +36,8 @@ class UnaryWordOperatorTestCase(TestCase):
36
36
  result = mathparse.parse('square root of 4', language='ENG')
37
37
 
38
38
  self.assertEqual(result, 2)
39
+
40
+ def test_negative_number(self):
41
+ result = mathparse.parse('-4 + 2')
42
+
43
+ self.assertEqual(result, -2)
File without changes
File without changes
File without changes
File without changes
File without changes