繁体   English   中英

使用Python查找字符串中多次出现的子串和字符的通用代码或Python函数?

[英]Generic code or Python function for finding multiple occurrences of substrings and character in string using Python?

我是Python的初学者。 我试图解决以下问题。 我在.txt文件中有一个SQL查询列表(例如):

SELECT first_name, last_name From table1 WHERE ID = 1234 AND date_of_birth = 19/01/1996;
SELECT last_name From table2 WHERE ID = 4563 AND date_of_birth =    10/04/1997 AND lisence_no = 2874;
SELECT first_name From table1 WHERE ID = 3762 AND age = 23 AND last_name = 'Maria';
SELECT first_name From table1 WHERE ID = 2894;

等等......现在我想在查询中将ID,last_name,lisence_no等特定值替换为“?”

所以我想得到这样的输出:

SELECT first_name, last_name From table1 WHERE ID = '?' AND date_of_birth = '?';
SELECT last_name From table2 WHERE ID = '?' AND date_of_birth = '?' AND lisence_no = '?';
SELECT first_name From table1 WHERE ID = '?' AND age = '?' AND last_name = '?';
SELECT first_name From table1 WHERE ID = '?';

我可以在python中使用什么函数来获取大量sql查询的这种类型的输出?

我知道像str.findstr.index这样的函数只能搜索一次,并且会涉及一些解决方法。 我期待一些专家python用户知道在我的情况下有用的函数或函数组合。

非常感谢!

我为此写了一个小脚本。 希望它能与你合作。

def replaceCustom(inputField, str):
    index = 0
    index2 = 1
    while(index<index2):
        index = str.find(inputField,index)
        index2 = str.find("AND",index2)

        str = str.replace((str[index:index2]), inputField+ " = '?' ")
        index +=1
        index2 +=1
        print (index, index2)

    return str     

str = """SELECT first_name, last_name From table1 WHERE ID = 1234 AND date_of_birth = 19/01/1996; 
SELECT last_name From table2 WHERE ID = 4563 AND date_of_birth =    10/04/1997 AND lisence_no = 2874;  
SELECT first_name From table1 WHERE ID = 3762 AND age = 23 AND last_name = 'Maria'; 
SELECT first_name From table1 WHERE ID = 2894;"""

str = replaceCustom("ID", str)
str = replaceCustom("date_of_birth", str)
str = replaceCustom("lisence_no", str)

我测试了它似乎工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM