【问题标题】:Generic code or Python function for finding multiple occurrences of substrings and character in string using Python?用于使用 Python 在字符串中查找多次出现的子字符串和字符的通用代码或 Python 函数?
【发布时间】:2016-05-23 15:47:36
【问题描述】:

我是 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 专家用户了解对我来说有用的函数或函数组合。

非常感谢!

【问题讨论】:

  • 您可能需要一个 sql 解析器(例如,旧问题:Parsing SQL with Python),或者如果您的输入足够规则,那么您可以使用正则表达式(re 模块)。或者,如果介于两者之间,那么您可以创建自己的语言来解析文件,code example
  • 你有没有注意到你要替换的所有数据都跟在= 符号后面。如果是整个文件的情况,那应该不会太难。

标签: python string


【解决方案1】:

我为此写了一个小脚本。希望它会和你一起工作。

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)

我测试了它,它似乎有效。

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多