python: 进阶 - 数据预处理 - 数据清洗 - 使用正则表达式,完成类似EXCEL的替换功能

前言:请优先使用string.replace,其次考虑re

例如:我们有内容如下的 haha.csv表。现在我想把含有移动的字段替换成另一个东西,比如你想换成yidong好了。怎么做呢?

0timeweizhi
120180101移动火车
220180101移动飞机
320180101移动椅子
420180101海面木板
520180101跟斗云
620180101梦幻空间
720180101黑洞
820180101擂台

Excel: 首先,我们“ctrl + h”调出查找替换对话框;然后,设定要查找的为移动*,要替换的为yidong;最后,点击确认就好了。

Python: python的思路大致相同思路。
第一步,读取有n列的haha.csv表,再逐行处理;
第二步,使用正则表达式查找含有 移动 的记录;
第三步,设定要替换的为yidong,再进行替换;
第四步,逐行逐行把替换好的记录添加到一块儿;
第五步,此时直接输出的csv仅为2列,需要调整格式,变为n列的csv文件。

第二版答案:

在第一版答案中,改进第二步第三步第四步,将代码由8行缩短为4行:

patterns = r'移动\w*'
regex = re.compile(patterns)
subplaced_data = regex.sub('yidong', line[i])
new_file.append(subplaced_data)

完整版:

import re
import pandas as pd


def tihuan():                                          # 设个函数,这样我们想运行它就调用它,不想就不调用。方便、主动。
    # 第一步:
    file = open('路径 + haha.csv', 'r')
    lines = file.readlines()
    new_file = []
    for i in range(len(lines)):
    # 第二步/第三步/第四步:
        patterns = r'移动\w*'
        regex = re.compile(pattern = patterns)
        subplaced_data = regex.sub('yidong', lines[i])  # re.sub('查找的字符', '替换的字符', '指查找替换发生的地方')
        new_file.append(subplaced_data)
     # 第五步:                                          # 没有这一步而直接.to_csv()的话,原表所有的列在新表里边全在一列。
        new_file_csvformat = []
        for i in new_file:
            new_line_split = i.split(',')
            new_file_csvformat.append(new_Line_split)
# 化为DataFrame格式,最后输出到指定位置
    final_file = pd.DataFrame(new_file_csvformat)
    final_file.to_csv('路径+新名字.csv', encoding='gbk', index=False, header=False) 
                                                        # index=False不添加index列,Header=False不添加column行即我们使用原列名称


if __name__ == '__main__':
    tihuan()

输出如下:

1timeweizhi
120180101yidong
220180101yidong
320180101yidong
420180101海面木板
520180101跟斗云
620180101梦幻空间
720180101黑洞
820180101擂台
第一版答案:
def tihuan():                                        # 设个函数,这样我们想运行它就调用它,不想就不调用。方便、主动。
    # 第一步:
    file = open('路径 + haha.csv', 'r')
    lines = file.readlines()
    new_file = []
    for i in range(len(lines)):
    # 第二步:
        patterns = r'移动\w*'
        regex = re.compile(pattern = patterns)
        search_data = regex.search(lines[i])
    # 第三步&第四步:
        if search:
            replaced_data = lines[i].replace(search_data.group(i), 'yidong')  # .group()用于正则表达式中,返回位置i的内容。本处即所有含有“移动”的地方;
           new_file.append(replaced_data)
        else:
            new_file.append(lines[i])
     # 第五步:
        new_file_csvformat = []
        for i in new_file:
            new_line_split = i.split(',')
            new_file_csvformat.append(new_Line_split)
      # 化为DataFrame格式,最后输出到指定位置
        final_file = pd.DataFrame(new_file_csvformat)
        final_file.to_csv(路径+新名字.csv', encoding='gbk')


if __name__ == '__main__':
    tihuan()

注:
.group() :正则表达式中,group()用来提出分组截获的字符串,()用来分组,例如

import re
a = "123abc456"
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)   #123abc456,返回整体
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)   #123
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)   #abc
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)   #456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值