
在文本处理中,我们经常需要从字符串中提取数字。然而,当数字以两种形式出现时——即阿拉伯数字(如 1, 2)和英文拼写形式(如 one, two)——问题变得复杂。更具挑战性的是,这些拼写形式的数字可能与其他字符混合,甚至出现重叠,例如在 "eightwothree" 中,我们期望识别出 '8' 和 '3',而在 "xtwone3four" 中,'two' 和 'one' 紧密相连,需要分别识别为 '2' 和 '1'。
示例问题: 考虑以下输入字符串及其期望的输出:
传统字符串替换方法的局限性: 初学者可能会尝试使用 str.replace() 方法将所有拼写数字替换为阿拉伯数字。例如:
tmp_string = line.strip()
tmp_string = tmp_string.replace("nine", "9")
tmp_string = tmp_string.replace("eight", "8")
# ...
tmp_string = tmp_string.replace("one", "1")这种方法存在明显缺陷:
为了解决这些问题,我们需要更精细的文本解析策略。
正则表达式(Regex)是处理字符串模式匹配的强大工具。通过巧妙地构造正则表达式,我们可以同时匹配阿拉伯数字和拼写数字,并处理重叠情况。
立即学习“Python免费学习笔记(深入)”;
核心概念:
实现步骤:
代码示例:extract_calibration_value 函数
import re
def extract_calibration_value(line: str) -> int:
"""
从字符串中提取第一个和最后一个数字(阿拉伯数字或拼写数字),
并将其组合成一个两位数。
能够处理重叠的拼写数字。
"""
# 建立拼写数字到阿拉伯数字的映射
word_to_digit = {
'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'
}
# 构建正则表达式模式。
# (?=...) 是一个正向先行断言,它允许匹配重叠的模式。
# 例如,对于 "twone",(?=(\d|two|one)) 可以匹配到 "two" 和 "one"。
# 我们捕获实际的匹配内容在第1组中。
pattern = r'(?=(\d|one|two|three|four|five|six|seven|eight|nine))'
# 查找所有匹配项,不区分大小写
matches = re.findall(pattern, line.lower())
if not matches:
# 如果没有找到任何数字,根据需求返回0或抛出异常
return 0
# 将匹配到的单词转换为数字
converted_digits = []
for match in matches:
if match.isdigit():
converted_digits.append(match)
else:
converted_digits.append(word_to_digit[match])
# 提取第一个和最后一个转换后的数字
first_digit = int(converted_digits[0])
last_digit = int(converted_digits[-1])
# 组合成两位数
return first_digit * 10 + last_digit
# 示例测试
test_lines = [
"two1nine",
"eightwothree",
"abcone2threexyz",
"xtwone3four",
"4nineeightseven2",
"zoneight234",
"7pqrstsixteen"
]
print("--- 正则表达式方案测试 ---")
for i, line in enumerate(test_lines):
value = extract_calibration_value(line)
print(f" Line {i+1}: '{line}' -> {value}")代码逻辑解释:
虽然上述正则表达式方法是解决特定问题(混合数字的精确提取)的有效方案,但Python生态系统中也存在专门用于将英文数字词语转换为数字的库,例如 word2number。这个库适用于将完整的英文数字短语(如 "eighty three" 或 "one hundred twenty-three")转换为其数值。
word2number 库介绍:word2number 是一个简洁的库,能够将用英文单词表示的数字转换为整数或浮点数。
安装:
pip install word2number
代码示例:words_to_digits 函数
from word2number import w2n
def words_to_digits(value: str):
"""
使用 word2number 库将完整的英文数字短语转换为数值。
"""
try:
number = w2n.word_to_num(value)
return number
except ValueError:
return None
print("\n--- word2number 库示例 ---")
# 示例:转换完整的数字短语
print(f"'eighty three' -> {words_to_digits('eighty three')}") # 输出: 83
print(f"'one hundred twenty-three' -> {words_to_digits('one hundred twenty-three')}") # 输出: 123
print(f"'seven' -> {words_to_digits('seven')}") # 输出: 7
# 尝试转换非完整数字短语,会失败
print(f"'eightwothree' -> {words_to_digits('eightwothree')}") # 输出: None (或抛出异常,取决于具体版本)
print(f"'two1nine' -> {words_to_digits('two1nine')}") # 输出: None重要提示:word2number 在本特定问题中的局限性word2number 库非常适合将 完整的、符合英语语法规则的数字短语 转换为数值。然而,它不适用于解析包含混合文本、部分拼写数字或需要识别重叠模式的任意字符串。例如,对于 eightwothree 或 xtwone3four 这样的输入,word2number 无法直接将其解析为 83 或 24,因为它期望的是一个完整的数字表达,而不是需要从复杂字符串中提取离散数字的场景。
因此,对于本文开头提出的特定问题(即从复杂字符串中提取第一个和最后一个阿拉伯数字或拼写数字),基于正则表达式的方案 (extract_calibration_value) 是更直接和有效的解决方案。word2number 可以作为辅助工具,如果你的任务是先将字符串中的某个子串识别为完整的数字短语,然后再进行转换。
将上述正则表达式方案整合到一个完整的程序中,使其能够读取文件并处理每一行,计算总和。
import re
import os # 导入os模块用于检查文件是否存在
def extract_calibration_value(line: str) -> int:
"""
从字符串中提取第一个和最后一个数字(阿拉伯数字或拼写数字),
并将其组合成一个两位数。
能够处理重叠的拼写数字。
"""
word_to_digit = {
'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'
}
# 构建正则表达式模式,使用正向先行断言 (?=...) 处理重叠匹配
pattern = r'(?=(\d|one|two|three|four|five|six|seven|eight|nine))'
matches = re.findall(pattern, line.lower())
if not matches:
return 0 # 如果没有找到任何数字,返回0
converted_digits = []
for match in matches:
if match.isdigit():
converted_digits.append(match)
else:
converted_digits.append(word_to_digit[match])
first_digit = int(converted_digits[0])
last_digit = int(converted_digits[-1])
return first_digit * 10 + last_digit
def main():
# 提示用户输入文件名
nomFichier = input('请输入文件名 (例如: input.txt): ')
if not nomFichier:
print("未输入文件名,程序退出。")
return
if not os.path.exists(nomFichier):
print(f"错误: 文件 '{nomFichier}' 不存在。")
return
print(f"正在打开文件: {nomFichier}")
total_sum = 0
try:
with open(nomFichier, 'r', encoding='utf-8') as file1: # 使用with语句确保文件正确关闭,并指定编码
lines = file1.readlines()
for line_num, line in enumerate(lines):
clean_line = line.strip() # 移除行首尾的空白字符和换行符
if not clean_line: # 跳过空行
continue
value = extract_calibration_value(clean_line)
print(f" 处理行 {line_num + 1}: '{clean_line}' -> 提取值: {value}")
total_sum += value
print(f"\n文件 '{nomFichier}' 的总和为: {total_sum}")
except Exception as e:
print(f"处理文件时发生错误: {e}")
if __name__ == "__main__":
main()使用方法:
two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen
python calibration_solver.py
程序将输出每行的处理结果和最终的总和。
总结: 本文详细介绍了如何在Python中从包含阿拉伯数字和英文拼写数字的混合字符串中提取首尾数字。通过深入分析传统字符串替换方法的局限性,我们推荐并演示了基于正则表达式的精确匹配方案,该方案利用零宽先行断言有效解决了重叠匹配的难题。同时,我们也介绍了 word2number 库作为将完整英文数字短语转换为数值的工具,并明确了其在本特定问题中的适用范围。掌握这些技术将有助于您在各种文本处理场景中更高效、更准确地提取数字信息。
以上就是Python字符串中数字与文字数字的鲁棒提取教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号