python正则表达式处理案例

import pandas as pd
import os,re
# 只需要替换尺寸文件内容就可以了
df=pd.read_excel(os.path.dirname(os.path.abspath(__file__))+'\尺寸.xlsx')
size=df['尺寸'].tolist()
# 正则表达式的使用
def deal(x):
    # 先判断是否为nan,nan为float类型
    if type(x)==float:
        return x
    # 再次判断是否是存在中文,中文不做任何处理
    elif len(re.findall('[\u4e00-\u9fa5]+',x))>=1:
        return x
    # 判断数字匹配是否大于3,大于3不做任何处理
    elif len(re.findall(r'\d+',x))>3:
        return x
    # 判断数字等于3时,进行对数字排序取最后两个进行拼接
    elif len(re.findall(r'\d+',x))==3:

        output = re.findall(r'\d+', x)
        # 做一个排序
        output = sorted([int(x) for x in output])
        return str(output[1]) + '*' + str(output[2])
    # 判断数字等于2时,进行对数字排序取进行拼接
    elif len(re.findall(r'\d+',x))==2:
        output=re.findall(r'\d+',x)
        # 做一个排序
        output=sorted([int(x) for x in output])
        return str(output[0])+'*'+str(output[1])
    # 判断数字等于1时,进行自定义处理
    elif len(re.findall(r'\d+',x))==1:
        output = re.findall(r'\d+', x)
        return '直径'+str(output[0])
    # 其他情况不做任何处理
    else:
        return x
df['尺寸']=[deal(x) for x in size]
df.to_excel(os.path.dirname(os.path.abspath(__file__))+'\尺寸处理后.xlsx',index=False)

对正则处理有疑问的可以和博主交流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金融小白数据分析之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值