替换字符串中的特定控件/不可打印字符

2024-05-15 05:44:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

输入:

'选择\n\ts.id\n\t、s.src\u cnt\n\t、s.out\u文件\t\n从\n\tkpi\u ros.s\n\t、kpi\u index\u rosoards d\n此处\n\t1=1\n\t和s.kpi\u rosoard\u id(+)=d.id\n\t和d.active=1\n;'

产出1:

'选择\n s.id\n、s.src\u cnt\n、s.out\u文件\n从\n kpi\u index\u ros.s\n、kpi\u index\u rosoards d\n此处\n 1=1\n和s.kpi\u index\u rosoard\u id(+)=d.id\n和d.active=1\n;'

产出2:

'从\tkpi_索引_ros.s\t、kpi_索引_ros.kpi_rosoards d中选择\ts.id\t、s.src_cnt\t、s.out_文件\t,其中\t1=1,s.kpi_索引_rosoards id(+)=d.id\tand.active=1;'

看起来它要么替换制表符,要么替换换行符,但不能同时替换两者。有没有办法以有效的方式实现这一点


Tags: 文件srcidsqlindexrosout制表符
1条回答
网友
1楼 · 发布于 2024-05-15 05:44:53

进行以下更改(将allSQL值替换为字符串对象的.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

相关问题 更多 >

    热门问题