You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现将句子中的数字转为英文单词?现有Python代码报错求助

数字转英文单词解决方案

原代码错误分析

你写的两段代码存在以下问题:

  • 第一段代码中,判断x in list_of_nums完全无效——输入文本里的是阿拉伯数字字符串(如"2"),但list_of_nums存的是英文单词,两者不匹配,永远不会进入替换分支;同时list_of_nums(x)是错误语法,列表不能通过函数调用的方式访问元素,且text_splt是空列表,调用其索引会触发越界错误。
  • 第二段代码逻辑混乱,arr未定义就调用arr.append(a),完全偏离了“数字转英文单词”的核心需求。

正确实现代码

方式一:基于列表索引实现(延续你的初始思路)

list_of_nums = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]

text = "2 apples and 6 pears"
words = text.split()
processed_words = []

for word in words:
    # 检查当前单词是否是0-9的数字字符串
    if word.isdigit() and int(word) < 10:
        # 数字转整数作为列表索引,取出对应英文单词
        processed_words.append(list_of_nums[int(word)])
    else:
        # 非数字单词直接保留
        processed_words.append(word)

# 拼接成最终句子
result = " ".join(processed_words)
print(result)  # 输出:two apples and six pears

方式二:基于字典映射实现(更直观简洁)

用字典直接建立数字字符串到英文单词的映射,代码更简洁:

num_to_word = {
    "0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
    "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"
}

text = "2 apples and 6 pears"
words = text.split()
# 用列表推导式快速处理每个单词,找不到对应映射就保留原单词
processed_words = [num_to_word.get(word, word) for word in words]
result = " ".join(processed_words)
print(result)

内容的提问来源于stack exchange,提问作者mars montgomery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:20:33