Python将英文数字单词字符串转换为整数的实现问题求助
英文数字单词转整数实现优化
现有代码的问题
你当前的实现仅对所有单词映射的数值做直接累加,没有兼容英文数字的层级计数逻辑,会在遇到hundred/thousand这类单位词时计算错误:
- 输入
two hundred,现有代码输出2 + 100 = 102,预期结果是2 * 100 = 200 - 输入
twenty thousand,现有代码输出20 + 1000 = 1020,预期结果是20 * 1000 = 20000 - 输入
one hundred and twenty three,现有代码无法处理连接词and,计算结果也不符合预期
优化思路
英文数字计数遵循分段逻辑,千位为一个大的分隔段,百位为段内的小分隔单位,按这个逻辑处理即可:
- 预处理输入:拆分所有空格、连字符分隔的单词,过滤无意义连接词
and - 维护两个计数变量:
total:存储最终累加的总数值current:存储当前千分段内的临时数值
- 遍历每个单词按规则计算:
- 遇到
thousand:将当前段数值乘以1000加到总数值,清空当前段临时值 - 遇到
hundred:将当前段临时值乘以100(因为是段内百倍单位) - 其他基础数字单词直接累加到当前段临时值
- 遇到
- 遍历结束后将剩余的当前段数值加到总数值,得到最终结果
优化后实现代码
def parse_int(string): num_map = { "zero":0, "one":1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9, "ten":10, "eleven":11, "twelve":12, "thirteen":13, "fourteen":14, "fifteen":15, "sixteen":16, "seventeen":17, "eighteen":18, "nineteen":19, "twenty":20, "thirty":30, "forty":40, "fifty":50, "sixty":60, "seventy":70, "eighty":80, "ninety":90, "thousand":1000, "hundred":100 } # 预处理:替换连字符为空格,拆分后过滤and words = string.replace('-', ' ').split() words = [w for w in words if w != 'and'] total = 0 current = 0 for word in words: val = num_map[word] if val == 1000: total += current * 1000 current = 0 elif val == 100: current *= 100 else: current += val total += current return total
测试验证
parse_int("one")→ 1,符合预期parse_int("two hundred")→ 200,符合预期parse_int("twenty thousand three hundred and forty five")→ 20345,符合预期parse_int("ninety-nine thousand nine hundred ninety-nine")→ 99999,符合预期
内容的提问来源于stack exchange,提问作者M.HBA
相关产品推荐
相关产品推荐

