登录
首页 >  文章 >  python教程

Python3中re模块无法直接转换数字和英文

时间:2026-02-22 19:44:52 378浏览 收藏

Python的re模块本身并不具备数字与英文单词相互转换的能力,它仅负责正则匹配与替换;真正的转换逻辑依赖于自定义映射字典(如0-9的对应关系)或第三方库(如inflect、num2words),再通过re.sub()配合lambda回调函数实现文本中数字与英文的智能替换——例如将句子中的“2”自动转为“two”,或将“three”精准替换为“3”,既简洁又实用,特别适合处理带数字的自然语言文本。

python3 re如何实现数字和英文的转换?

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><h1>使用正则匹配单个数字</h1><pre class="brush:php;toolbar:false"><code>return re.sub(r'\d', lambda match: num_to_word[match.group(0)], text)</code>

测试

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.
</p>

注意事项

  • 上述例子仅处理 0-9,若需支持更大数字(如 twenty, hundred),需扩展映射逻辑或使用第三方库如 num2wordsword2number
  • \b 表示词边界,避免匹配到像 "ones" 中的 "one"。
  • 正则只是工具,真正“转换”靠的是映射字典和替换函数。

基本上就这些。用 re 做这种转换的关键是配合 re.sub() 和回调函数,实现灵活替换。不复杂但容易忽略细节。

理论要掌握,实操不能落!以上关于《Python3中re模块无法直接转换数字和英文》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>