Python_读取文件替换字符

字符串

字符串的移除换行符 两边空格
列表变为字符串 列表变为字典 列表的追加
读取文件 跳过首行
利用列表和字典生成替换的功能

知识点

 参数:
  return func(x, *args, **kwargs)
  *args表示任何多个无名参数,它是一个tuple;
  **kwargs表示关键字参数,它是一个dict。
  并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前
apply自定义函数
 apply不仅可以对列进行操作还可以对行进行操作,只需要对apply传递一个参数axis=0
 在apply里加上args=,将其他参数组成一个元组代入函数中。
 但有个前提:被调用的函数第一个参数必须是DataFrame的行或列,args=的元组中参数位置必须和函数定义的参数位置一致
  以下代码--使用自带的库编写 和使用pandas 实现数据预处理的两种方案

代码示例

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import pandas as pd


def nm_relation():
    """列表创建字典"""
    nm_list1 = ['晴','雨','阴' ]
    nm_list2 = ['sunny','rainy','cloudy']
    nm_relation_match = dict(zip(nm_list1,nm_list2))
    return nm_relation_match


def get_code_nm(file_nm):
    nm_dep = nm_relation()
    print(nm_dep)
    with open(file=file_nm,mode='r',encoding="utf8") as f:
        # 使用next函数 跳过首行
        first_line = next(f)
        for num, data in enumerate(f):
            steList = data.strip().replace("\r","").replace("\n","").split("\t")
            # 利用字典对指定文本字符串进行替换
            res = []
            for key_data in steList[3].split("_"):
                res.append(nm_dep[key_data])
            out_label = "_".join(res)
            #拼接字符串
            dir_nm = "_".join((steList[1],steList[4],out_label))
            steList.append(dir_nm)
            print(num,steList)


def get_code_nm_df(file_nm):
    nm_dep = nm_relation()
    print(nm_dep)
    re_df = pd.read_csv(file_nm,sep="\t",encoding="utf8")
    # 用字典形式替换多个值
    data_re = re_df["标签"].str.split('_', expand=True).replace(nm_dep)
    # 多列合并为一列
    date_result = data_re[0].str.cat(data_re[1],sep="_").str.cat(data_re[2],sep="_")
    result_df = re_df["data集"].str.cat(re_df["ren次"].map(str),sep="_").str.cat(date_result,sep="_")
    # Series 变为数据框且命名
    result_df = result_df.to_frame(name="new_label")
    # 拼接列
    result = pd.concat([result_df,re_df], axis=1)
    # 保存数据
    result.to_csv(r"H:\data\test\group_result.txt",index=False,header=True,sep="\t")


if __name__ == "__main__":
    base_file_nm = r"H:\data\test\test.txt"
    #get_code_nm(base_file_nm)
    get_code_nm_df(base_file_nm)

参考

python3.5学习笔记--利用字典对指定文本字符串进行替换 https://www.cnblogs.com/liujian001/p/5145016.htm
给DataFrame的apply调用的函数添加多个参数 https://blog.csdn.net/jewely/article/details/107888098
Python3 pandas(19) 替换 replace()及部分替换 https://zhuanlan.zhihu.com/p/308293
Python3跳过第一行读取文件内容 https://blog.csdn.net/larry233/article/details/82907042
原文地址:https://www.cnblogs.com/ytwang/p/15601687.html