答案是Python的re模块通过结合正则表达式和映射字典实现数字与英文单词的相互转换,具体使用re.sub()配合回调函数完成替换操作。

Python 的 re 模块本身不直接提供数字和英文之间的“转换”功能,它是一个正则表达式模块,用于字符串的匹配、查找、替换等操作。如果你所说的“数字和英文的转换”是指在文本中识别数字并替换成对应的英文单词(如 1 → one),或者反过来(one → 1),你可以结合 re 和自定义映射来实现。
1. 数字转英文单词(例如:1 → "one")
需要先定义一个映射表,然后使用 re.sub() 替换所有匹配到的数字。
示例代码:
import re
<h1>定义数字到英文单词的映射(这里只处理 0-9)</h1><p>num_to_word = {
'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'
}</p><p>def replace_digits_with_words(text):</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><h1>使用正则匹配单个数字</h1><pre class="brush:php;toolbar:false;">return re.sub(r'\d', lambda match: num_to_word[match.group(0)], text)
测试
text = "I have 2 apples and 3 bananas." result = replace_digits_with_words(text) print(result) # 输出: I have two apples and three bananas.
2. 英文单词转数字(例如:one → 1)
同样使用 re.sub(),但这次匹配英文单词。
示例代码:
import re
<h1>英文单词到数字的映射</h1><p>word_to_num = {
'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'
}</p><h1>构造正则表达式,匹配这些单词(完整词边界)</h1><p>pattern = r'\b(' + '|'.join(word_to_num.keys()) + r')\b'</p><p>def replace_words_with_digits(text):
return re.sub(pattern, lambda match: word_to_num[match.group(0)], text)</p><h1>测试</h1><p>text = "I have two apples and three bananas."
result = replace_words_with_digits(text)
<strong>print(result)</strong> # 输出: I have 2 apples and 3 bananas.
注意事项
- 上述例子仅处理 0-9,若需支持更大数字(如 twenty, hundred),需扩展映射逻辑或使用第三方库如
num2words或word2number。 -
\b表示词边界,避免匹配到像 "ones" 中的 "one"。 - 正则只是工具,真正“转换”靠的是映射字典和替换函数。
基本上就这些。用 re 做这种转换的关键是配合 re.sub() 和回调函数,实现灵活替换。不复杂但容易忽略细节。











