Python 的数字字符串类型清洗有什么好方法吗?

最近一直在处理 字符串类型的数字 比如‘ 19 万 4000 ’转为 194000 这样的整形 我只会采用笨方法转换 来问问大佬们都有什么好方法 处理字符串转数字 先谢~


Python 的数字字符串类型清洗有什么好方法吗?
5 回复

Google 搜 “ python 汉字转阿拉伯数字” 可有很多参考结果,下面只列出一个有 github 项目的案例:

python 工具脚本:chinese_digit.py - 中文数字 转换为 阿拉伯数字 | Binuxの杂货铺 :
https://binux.blog/2011/03/python-tools-chinese-digit/


处理数字字符串清洗,我常用这几个方法:

  1. 基础去空格:直接用 strip() 去掉前后空格
s = " 123 "
clean = s.strip()  # "123"
  1. 处理千分位和货币符号:用 replace() 链式操作
s = "$1,234.56"
clean = s.replace('$', '').replace(',', '')  # "1234.56"
  1. 正则表达式处理复杂情况:提取所有数字和小数点
import re

def clean_number_string(s):
    # 匹配数字、小数点和负号
    matches = re.findall(r'-?\d*\.?\d+', str(s))
    return matches[0] if matches else None

# 示例
print(clean_number_string("Price: $1,234.56"))  # "1234.56"
print(clean_number_string("-123.45 units"))     # "-123.45"
  1. 转换数字类型:清洗后直接转成 int 或 float
def to_number(s):
    try:
        cleaned = re.sub(r'[^\d.-]', '', str(s))
        return float(cleaned) if '.' in cleaned else int(cleaned)
    except ValueError:
        return None

# 示例
print(to_number("1,234.56"))  # 1234.56
print(to_number("42"))        # 42
  1. 处理科学计数法
s = "1.23e+4"
clean = float(s)  # 12300.0

简单建议:根据数据复杂度选择合适方法,正则表达式最通用。

是什么笨办法呢?

就是分割 然后 int 转换 再加起来 这种 基本操作🤦‍♀️

回到顶部