After Introducing The E-Notation The Text Functions Do Not Work Anymore. The buttons work and if i press them i get the right text in the execution field. But if i press enter to execute the command (for example: capitalize(tree) or duplicates(tree tree)) nothing happens. I also get the following Error: Traceback (most recent call last):
File "D:\Bilder\Python\0. Code\Calculator 16.py", line 293, in calculate
result = evaluate_expression(expression, use_degrees=self.use_degrees, use_e_notation=self.use_e_notation)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Bilder\Python\0. Code\Calculator 16.py", line 122, in evaluate_expression
expression = preprocess_text_functions(expression)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Bilder\Python\0. Code\Calculator 16.py", line 87, in preprocess_text_functions
return re.sub(r'\b(capitalize|duplicates)(([^)]+))', add_quotes, expression)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Zarathustra\AppData\Local\Programs\Python\Python312\Lib\re_init_.py", line 186, in sub
return _compile(pattern, flags).sub(repl, string, count)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Bilder\Python\0. Code\Calculator 16.py", line 85, in add_quotes
func, args = match.groups()
^^^^^^^^^^
ValueError: too many values to unpack (expected 2) Python 3.12 code: import math
import re
from typing import Any, Union, Callable
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt
-- Utility Functions --
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Convert angle based on degree mode."""
return func(math.radians(x) if use_degrees else x)
-- Conversions Category --
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines from a string."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions to ensure proper quoting of arguments."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
return re.sub(r'\b(capitalize|duplicates)(([^)]+))', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Validate inputs for inverse trigonometric functions."""
for func, arg in re.findall(r"(\b\w+\b)(([^)]+))", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate the expression and format the result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
if use_e_notation:
# Format using scientific notation with up to 2 decimal places
result = f"{result:.2e}"
else:
# Standard formatting with rounding
result = round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
The error you're encountering stems from the regular expression (regex) used in the preprocess_text_functions function. Specifically, the regex is capturing more groups than intended, leading to a ValueError when trying to unpack the matched groups. Let's walk through the issue and provide a solution.
Understanding the Error
Error Message:
code
ValueError: too many values to unpack (expected 2)
Traceback Analysis:
The error occurs in the add_quotes function within preprocess_text_functions.
The regex pattern r'\b(capitalize|duplicates)(([^)]+))' is intended to capture two groups:
The function name (capitalize or duplicates).
The arguments passed to the function.
However, due to the nested parentheses in the regex, it actually captures three groups:
Group 1:(capitalize|duplicates) – captures the function name.
Group 2:(([^)]+)) – captures the entire argument string including the parentheses.
Group 3:([^)]+) – captures the arguments inside the parentheses.
When match.groups() is called, it returns all three groups, but the code expects only two (func and args), causing the ValueError.
Solution
1. Correct the Regular Expression
To fix the issue, modify the regex to capture only the necessary groups:
Group 1: The function name (capitalize or duplicates).
Group 2: The arguments inside the parentheses without capturing the parentheses themselves.
Updated Regex Pattern:
python
r'\b(capitalize|duplicates)\(([^)]+)\)'
Explanation:
\b(capitalize|duplicates): Matches the function name with a word boundary to ensure it doesn't match substrings.
\( and \): Match the literal opening and closing parentheses.
([^)]+): Captures all characters inside the parentheses except the closing parenthesis.
2. Update the preprocess_text_functions Function
Replace the existing regex pattern with the corrected one. Here's the updated function:
python
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions to ensure proper quoting of arguments."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
# Updated regex pattern with only two capturing groups
return re.sub(r'\b(capitalize|duplicates)\(([^)]+)\)', add_quotes, expression)
3. Complete Corrected Code Snippet
Here's the modified section of your code with the corrected regex:
python
Testing the Fix
To ensure the fix works as intended, consider the following test cases:
Capitalizing a Phrase:
Input:capitalize(tree)
Expected Output:Tree
Removing Duplicates:
Input:duplicates(tree tree)
Expected Output:tree
Combining with E-Notation:
Input:capitalize(branches) + 2e3
Expected Output:Branches + 2000.00 (formatted according to E-Notation settings)
Additional Recommendations
Enhance Regex Robustness:
Ensure that the regex can handle nested functions or multiple arguments if needed.
Consider using word boundaries and stricter matching to avoid unintended replacements.
Error Handling:
Provide user-friendly error messages when invalid inputs are detected.
For example, if the user inputs capitalize( without closing the parenthesis, handle it gracefully.
Input Sanitization:
Sanitize inputs to prevent potential security vulnerabilities, especially since eval is used.
Although safe_globals restricts the available functions, always be cautious with eval.
Unit Testing:
Implement unit tests for preprocess_text_functions to cover various scenarios.
This helps in maintaining code reliability as the application evolves.
Logging:
Implement logging to capture unexpected behaviors without crashing the application.
This aids in debugging future issues.
Conclusion
By correcting the regular expression in the preprocess_text_functions function, you eliminate the ValueError caused by mismatched group captures. This fix ensures that your text functions (capitalize and duplicates) work seamlessly, even after introducing E-Notation. Always remember to test thoroughly after making such changes to confirm that all functionalities behave as expected.
If you continue to face issues or have further questions, feel free to ask!
Not yet included in a published release.
import math
import re
from typing import Any, Union, Callable
# ... [rest of your imports and utility functions] ...
# -- Processing --
def get_safe_globals(use_degrees: bool) -> dict:
"""Return a dictionary of safe globals for expression evaluation."""
trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'}
safe_globals = {
"sqrt": math.sqrt,
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kilograms_to_pounds,
"kg": pounds_to_kilograms,
"C": kelvin_to_celsius,
"K": celsius_to_kelvin,
"F": celsius_to_fahrenheit,
"CF": fahrenheit_to_celsius,
"capitalize": capitalize_sentence,
"duplicates": remove_duplicates,
}
safe_globals.update({
func: (lambda f: (lambda x, f=f: convert_angle(getattr(math, f), x, use_degrees)))(func)
for func in trig_funcs.union({'asin', 'acos'})
})
return safe_globals
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions to ensure proper quoting of arguments."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
# Corrected regex with only two capturing groups
return re.sub(r'\b(capitalize|duplicates)\(([^)]+)\)', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Validate inputs for inverse trigonometric functions."""
for func, arg in re.findall(r"(\b\w+\b)\(([^)]+)\)", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate the expression and format the result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
if use_e_notation:
# Format using scientific notation with up to 2 decimal places
result = f"{result:.2e}"
else:
# Standard formatting with rounding
result = round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
def evaluate_expression(expression: str, use_degrees: bool = False, use_e_notation: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
safe_globals = get_safe_globals(use_degrees)
expression = expression.replace("^", "**")
expression = preprocess_text_functions(expression)
error = validate_inverse_trig(expression, safe_globals)
return error or safe_evaluate(expression, safe_globals, use_e_notation)
# ... [rest of your GUI code] ...