Python数学文字题计算:字典取值返回None的问题排查与解决
解决数学文字题脚本的键查找与运算处理问题
问题根源
- 键类型不匹配:你用
numbers.get(result)时,result是一个元组(比如('two', 'times', 'three')),但字典numbers的键都是字符串(单个单词或'divided by'),元组无法匹配任何键,所以返回None。 - 多单词运算符未处理:
'divided by'是两个单词,直接用split()会被拆成'divided'和'by',导致无法正确识别运算符。
修正后的代码
import operator # 定义数字单词到数值、运算符单词到运算函数的映射 numbers = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'plus': operator.add, 'minus': operator.sub, 'times': operator.mul, 'divided_by': operator.truediv } # 获取用户输入并统一转为小写,避免大小写问题 word_problem = input('Type your word problem in this format: "What is two times three" ').lower() # 提取"What is"之后的运算部分 if 'what is' in word_problem: _, _, problem_part = word_problem.rpartition('what is ') else: print("输入格式错误,请遵循指定格式") exit() # 处理多单词运算符"divided by",替换为单单词占位符,避免split拆分 problem_part = problem_part.replace('divided by', 'divided_by') # 拆分运算部分为单词列表 parts = problem_part.split() # 验证拆分后的结构是否符合要求(数字、运算符、数字) if len(parts) != 3: print("输入格式错误,请输入类似'What is two times three'的问题") exit() # 从字典中获取对应的数值和运算函数 num1 = numbers.get(parts[0]) op = numbers.get(parts[1]) num2 = numbers.get(parts[2]) # 验证所有元素是否有效 if None in (num1, op, num2): print("输入包含无效的数字或运算符") exit() # 执行运算并输出结果 result = op(num1, num2) print(f"计算结果:{result}")
代码说明
- 统一大小写:将输入转为小写,确保匹配字典中的键(比如用户输入"Two"也能识别)。
- 处理多单词运算符:把
'divided by'替换为'divided_by',这样split()后能作为单个元素识别,之后从字典中获取对应的除法函数。 - 拆分与验证:拆分后检查结构是否为「数字单词 + 运算符 + 数字单词」,避免无效输入。
- 分步查找键:分别提取三个部分的内容,用各自的字符串去字典中查找对应的值和函数,而不是用整个元组查找。
测试示例
- 输入:
What is two times three→ 输出:计算结果:6 - 输入:
What is seven minus five→ 输出:计算结果:2 - 输入:
What is eight divided by two→ 输出:计算结果:4.0
内容的提问来源于stack exchange,提问作者lavender_frog
相关产品推荐
相关产品推荐

