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

如何使用num2words将字符串中的阿拉伯数字转换为英文单词

解决方案

实现思路

借助Python正则表达式的re.sub()方法的回调替换能力,匹配到文本中的数字后直接调用num2words完成转换,自动替换回原位置,天然支持单条文本内多个数字的批量处理。

前置依赖

安装num2words库:

pip install num2words

完整实现代码

import re
from num2words import num2words

def num_to_word_replace(text):
    # 匹配所有正整数,调用num2words转换为美式英文单词后替换
    return re.sub(r'\d+', lambda m: num2words(int(m.group()), lang='en_US'), text)

# 示例输入
list_string = ['I spent 140 dollar yesterday','I have 3 brothers and 2 sisters']
# 批量处理列表
output_string = [num_to_word_replace(s) for s in list_string]

# 输出验证
print(output_string)

执行输出

['I spent one hundred forty dollar yesterday', 'I have three brothers and two sisters']

补充说明

当前实现仅匹配整数数字,完全匹配你无需处理浮点数、特殊年份的使用需求。如果需要英式拼写带and的数字表述,去掉num2words的lang='en_US'参数即可。

内容的提问来源于stack exchange,提问作者Vinson Ciawandy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:54:07