替换字符串中的特定 control/non-printable 个字符

Replace specific control/non-printable characters from string

我正在编写读取 sql 文件并使用 cx_Oracle 执行文件的脚本。有些文件仅在每个 sql 运算符和关键字之间使用空格编写,而其他文件则使用换行符和制表符作为空白。我面临着后者的问题。例如本节returns以下:

NON_PRINTABLE = """\r\n\t"""
def parseSQLFile(filename):
    with open(filename, 'r') as sqlFile:
        allSQL = sqlFile.read()
        #filteredSQL = filter(lambda ln: ln in string.printable, allSQL)
        # replace specific control characters with spaces to prevent sql compiler errors
        for char in NON_PRINTABLE:
            allSQL.replace(char,' ')


    return allSQL

我试过使用过滤功能,翻译,替换;但是,我仍然从以下输入中得到以下不同的结果:

输入:

'select\n\ts.id\n\t,s.src_cnt\n\t,s.out_file\t\nfrom\n\tkpi_index_ros.composites s\n\t,kpi_index_ros.kpi_index_rosoards d\nwhere\n\t1 = 1\n\tand s.kpi_index_rosoard_id (+) = d.id\n\tand d.active = 1\n;'

输出 1:

'select\n s.id\n ,s.src_cnt\n ,s.out_file \nfrom\n kpi_index_ros.composites s\n ,kpi_index_ros.kpi_index_rosoards d\nwhere\n 1 = 1\n and s.kpi_index_rosoard_id (+) = d.id\n and d.active = 1\n;'

输出 2:

'select \ts.id \t,s.src_cnt \t,s.out_file\t from \tkpi_index_ros.composites s \t,kpi_index_ros.kpi_index_rosoards d where \t1 = 1 \tand s.kpi_index_rosoard_id (+) = d.id \tand d.active = 1 ;'

它似乎会替换制表符或换行符,但不会同时替换两者。有什么方法可以有效地完成这个任务吗?

进行以下更改(将 allSQL 值替换为 String 对象的 .replace 方法的输出)产生所需的输出:

NON_PRINTABLE = """\r\n\t"""
def parseSQLFile(filename):
    with open(filename, 'r') as sqlFile:
        allSQL = sqlFile.read()
        # replace specific control characters with spaces to prevent sql compiler errors
        for char in NON_PRINTABLE:
            allSQL = allSQL.replace(char,' ') #updating allSQL with returned value

    return allSQL

输出:

'select  s.id  ,s.src_cnt  ,s.out_file  from  kpi_index_ros.composites s  ,kpi_index_ros.kpi_index_rosoards d where  1 = 1  and s.kpi_index_rosoard_id (+) = d.id  and d.active = 1 ;'

关于您问题的第二部分 - 关于这种方法的效率,您可能应该参考 benchmark results in this answer