A library for solving mathematical equations contained in strings with multi-language support.
npx @tessl/cli install tessl/pypi-mathparse@0.2.0Mathparse is a Python library for solving mathematical equations contained in strings, supporting both numeric expressions and natural language mathematical phrases in multiple languages. It provides a simple, unified API for evaluating mathematical expressions from user input, text processing systems, and NLP applications.
pip install mathparsefrom mathparse import mathparseFor accessing constants and language utilities:
from mathparse import mathwordsThe mathparse package provides access to functionality through two main modules:
mathparse.mathparse: Core parsing and evaluation functions (imported as mathparse)mathparse.mathwords: Language dictionaries, constants, and utility functions (imported as mathwords)from mathparse import mathparse
# Basic numeric expressions
result = mathparse.parse('50 * (85 / 100)')
# Returns: 42.5
# Natural language expressions (requires language parameter)
result = mathparse.parse('nine times nine', language='ENG')
# Returns: 81
# Mixed numeric and word expressions
result = mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
# Returns: 24
# Extracting expressions from noisy text
expression = mathparse.extract_expression('What is 4 + 4?', language='ENG')
# Returns: '4 + 4'
result = mathparse.parse(expression)
# Returns: 8Evaluates mathematical expressions from strings, supporting standard arithmetic operations and natural language mathematical phrases.
def parse(string, language=None):
"""
Return a solution to the equation in the input string.
Args:
string (str): Mathematical expression as string (e.g., "4 + 4" or "four plus four")
language (str, optional): ISO 639-2 language code for natural language support
Returns:
number: Computed result (int, float, or Decimal for division)
"""Extracts mathematical expressions from noisy text, filtering out non-mathematical content.
def extract_expression(dirty_string, language):
"""
Extract mathematical expression from text containing non-mathematical content.
Args:
dirty_string (str): Text containing mathematical expression
language (str): ISO 639-2 language code for word recognition
Returns:
str: Cleaned mathematical expression
"""Converts string expressions into lists of mathematical tokens for processing.
def tokenize(string, language=None, escape='___'):
"""
Convert string into list of mathematical symbol tokens.
Args:
string (str): Input mathematical expression
language (str, optional): ISO 639-2 language code for word recognition
escape (str): Character sequence for escaping spaces in multi-word phrases
Returns:
list: List of mathematical tokens
"""Utility functions for checking whether strings represent specific mathematical elements.
def is_int(string):
"""
Check if string represents an integer.
Args:
string (str): String to check
Returns:
bool: True if string is an integer
"""
def is_float(string):
"""
Check if string represents a float.
Args:
string (str): String to check
Returns:
bool: True if string is a float
"""
def is_constant(string):
"""
Check if string is a mathematical constant.
Args:
string (str): String to check
Returns:
bool: True if string is a mathematical constant (pi, e)
"""
def is_unary(string):
"""
Check if string is a unary mathematical operator.
Args:
string (str): String to check
Returns:
bool: True if string is a unary operator (sqrt, log)
"""
def is_binary(string):
"""
Check if string is a binary mathematical operator.
Args:
string (str): String to check
Returns:
bool: True if string is a binary operator (+, -, *, /, ^)
"""
def is_symbol(string):
"""
Check if string is any mathematical symbol.
Args:
string (str): String to check
Returns:
bool: True if string is a mathematical symbol
"""
def is_word(word, language):
"""
Check if word is a mathematical word in the specified language.
Args:
word (str): Word to check
language (str): ISO 639-2 language code
Returns:
bool: True if word is a math word in the language
"""Access to language-specific mathematical vocabularies and word-to-symbol mappings.
# Available through mathparse.mathwords module
def word_groups_for_language(language_code):
"""
Get complete word groups for a language code.
Args:
language_code (str): ISO 639-2 language code
Returns:
dict: Dictionary containing numbers, operators, and scales for the language
Raises:
InvalidLanguageCodeException: If language code is not supported
"""
def words_for_language(language_code):
"""
Get all mathematical words for a language code.
Args:
language_code (str): ISO 639-2 language code
Returns:
list: List of all mathematical words in the language
Raises:
InvalidLanguageCodeException: If language code is not supported
"""Internal processing functions for postfix notation and expression evaluation.
def replace_word_tokens(string, language):
"""
Replace word tokens with numeric equivalents.
Args:
string (str): String containing word tokens
language (str): ISO 639-2 language code
Returns:
str: String with words replaced by numeric operators
"""
def to_postfix(tokens):
"""
Convert list of tokens to postfix notation.
Args:
tokens (list): List of mathematical tokens
Returns:
list: Tokens in postfix notation
"""
def evaluate_postfix(tokens):
"""
Evaluate tokens in postfix notation.
Args:
tokens (list): Tokens in postfix notation
Returns:
number: Computed result
Raises:
PostfixTokenEvaluationException: If evaluation fails
"""
def find_word_groups(string, words):
"""
Find word group patterns for scaling (e.g., "3 thousand 6 hundred").
Args:
string (str): Input string
words (list): List of scaling words to match
Returns:
list: List of matched word group patterns
"""The library supports mathematical expressions in the following languages (ISO 639-2 codes):
Each language includes:
# Access mathematical constants
from mathparse import mathwords
CONSTANTS = mathwords.CONSTANTS
# Returns: {'pi': 3.141693, 'e': 2.718281}# Access unary mathematical functions
from mathparse import mathwords
UNARY_FUNCTIONS = mathwords.UNARY_FUNCTIONS
# Returns: {'sqrt': math.sqrt, 'log': math.log10}# Access available language codes
from mathparse import mathwords
LANGUAGE_CODES = mathwords.LANGUAGE_CODES
# Returns: ['ENG', 'FRE', 'GER', 'GRE', 'ITA', 'MAR', 'RUS', 'POR']High-precision decimal arithmetic class used for division operations to maintain precision.
# Decimal type used by mathparse (from Python's decimal module)
from decimal import Decimal
class Decimal:
"""
High-precision decimal arithmetic class used for division operations.
Used internally by mathparse to avoid floating-point precision issues.
Results from division operations return Decimal objects.
"""
def __init__(self, value):
"""Create Decimal from string or number."""
def __str__(self):
"""Return string representation."""
# Supports standard arithmetic operations: +, -, *, /, ==, etc.# Available through mathparse import
from mathparse import mathparse
class PostfixTokenEvaluationException(Exception):
"""
Exception raised when postfix token evaluation fails.
Common causes: unknown tokens, empty expression stack, malformed expressions.
"""
# Available through mathwords import
from mathparse import mathwords
class InvalidLanguageCodeException(Exception):
"""
Exception raised when an unsupported ISO 639-2 language code is provided.
"""from mathparse import mathparse, mathwords
try:
result = mathparse.parse('invalid expression')
except mathparse.PostfixTokenEvaluationException as e:
print(f"Expression evaluation failed: {e}")
try:
words = mathwords.words_for_language('XXX')
except mathwords.InvalidLanguageCodeException as e:
print(f"Invalid language code: {e}")
# Division by zero returns 'undefined' string rather than raising exception
result = mathparse.parse('5 / 0')
# Returns: 'undefined'from mathparse import mathparse
# Large number expressions with scales
result = mathparse.parse('four thousand two hundred one plus five hundred', language='ENG')
# Returns: 4701
# Mixed operations with parentheses
result = mathparse.parse('(seven * nine) + 8 - (45 plus two)', language='ENG')
# Returns: 24
# Power operations
result = mathparse.parse('two to the power of three', language='ENG')
# Returns: 8
# Constants and functions
result = mathparse.parse('sqrt 25')
# Returns: 5.0
result = mathparse.parse('pi * 2')
# Returns: 6.283386from mathparse import mathparse
# Extract and evaluate from natural text
user_input = "Can you tell me what is 15 plus 27?"
expression = mathparse.extract_expression(user_input, language='ENG')
# Returns: '15 plus 27'
result = mathparse.parse(expression, language='ENG')
# Returns: 42
# Multi-language support
result = mathparse.parse('vingt plus trente', language='FRE')
# Returns: 50
result = mathparse.parse('zwanzig plus dreißig', language='GER')
# Returns: 50